-1

I want to read all files in specific directory. for example In directory a there are file1.text file2.txt a.txt c.txt

I want to know how many words are included in each file. I made a code for a file. But I don't know how to automatically move on next file at same directory.

int EBook::get_total_words() {

ifstream ifs("inputs//a.txt");
int words = 0;
string word;

if (!ifs)
{
    std::cout << "Unable to open file " << '\n';
    exit(1);
}

while (ifs >> word) {
    ++words;
}


return words;

}

  • Does this answer your question? [How can I get the list of files in a directory using C or C++?](https://stackoverflow.com/questions/612097/how-can-i-get-the-list-of-files-in-a-directory-using-c-or-c) – Ulrich Eckhardt Mar 18 '22 at 07:54

1 Answers1

0

With std::filesystem you can do this:

std::string path_to_dir = '/some/path/';
for( const auto & entry : std::filesystem::directory_iterator( path_to_dir ) ){
    std::cout << entry.path( ) << std::endl;
}
no more sigsegv
  • 468
  • 5
  • 17
  • Thanks for helping. I also searched this code but I can't understand how to operate this code. Is there any websites that i can search to understand? – SWDEVELOPERFROMKR Mar 18 '22 at 08:14
  • @SWDEVELOPERFROMKR - The code snippet will list all the file names in the directory. Surely you can figure out how to *open* the file instead of displaying the name. – BoP Mar 18 '22 at 08:19
  • 1
    @SWDEVELOPERFROMKR please explain how can you not operate the code so we can help. This is a minimal example to show you how to obtain path of each file in a directory. As BoP said, you are going to need to do what you actually want inside that for loop. With each iteration, you will get a different file's path from `entry.path()` so you can do whatever you want with it. I just gave a basic example of printing their names. Don't forget adding `#include ` and compiling with `-std=c++17` . – no more sigsegv Mar 18 '22 at 08:29
  • 1
    @SWDEVELOPERFROMKR you will need to `#include ` and use a C++17 or later compiler – Caleth Mar 18 '22 at 08:38
  • @nomoresegmentationfaults Thanks and sorry for late replying for example if i have a.txt, b.txt c.txt d.txt file in a same directory then how can i adjust above code to count words? – SWDEVELOPERFROMKR Mar 19 '22 at 06:47