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?