0

I am trying to read all txt files from a folder, including the txt files from subdirectories of the selected folder using C++.

I implemented a version of the program, that reads all text files from a specific folder, but does not iterate to all subfolders.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <dirent.h>

using namespace std;

int main() {

    DIR*     dir;
    dirent*  pdir;

    dir = opendir("D:/");     // open current directory

    int number_of_words=0;
    int text_length = 30;
    char filename[300];
    while (pdir = readdir(dir)) 
    {
        cout << pdir->d_name << endl;
        strcpy(filename, "D:/...");
        strcat(filename, pdir->d_name);
        ifstream file(filename);
        std::istream_iterator<std::string> beg(file), end;

        number_of_words = distance(beg,end);

        cout<<"Number of words in file: "<<number_of_words<<endl;
        ifstream files(filename);
        char output[30];
        if (file.is_open()) 
        {
            while (!files.eof())
            {
                    files >> output;
                    cout<<output<<endl;
            }
        }
        file.close();
    }
    closedir(dir);
    return 0;
}

What should I modify to this program to search for txt files in subfolders of the selected folder too?

Alex Iacob
  • 33
  • 3
  • 12

2 Answers2

0

I found here a way to check if a file is a directory: Accessing Directories in C

What you should do first is to put your code inside a function, lets say, void f(char *dir), so that you can process multiple folders. Then use the code provided in the above link to find whether a file is a directory or not.

If it's a directory, call f on it, if it's a txt file do what you want to do.

Be careful about one thing: in each directory there are directories that will send you to an infinite loop. "." points to your current directory, ".." points to the parent directory and "~" points to home directory. You'll probably want to exclude these ones. http://en.wikipedia.org/wiki/Path_%28computing%29

Community
  • 1
  • 1
SlySherZ
  • 1,631
  • 1
  • 16
  • 25
0

The simplest way is to write a read_one_file() function, and recursively call it.

read_one_file() looks like this:

read_one_file(string filename){
    if(/* this file is a directory */){
        opendir(filename);
        while(entry=readdir){
            read_one_file(/*entry's filename*/);
        }
    }else{ /* this file is a regular file */
        /* output the file */
    }
}
Min Fu
  • 789
  • 1
  • 6
  • 16
  • read_one_file() many times not supported to c++ 11 and lower. Check this https://stackoverflow.com/a/69554425/12214121 – Omkar Oct 13 '21 at 11:12