我正在尝试从文件夹中读取所有txt文件,包括使用C++选定文件夹的子目录中的txt文件。如何读取文件夹中的所有txt文件? (包括子文件夹)
我实现了该程序的一个版本,它读取特定文件夹中的所有文本文件,但不会迭代到所有子文件夹。
#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;
}
我应该修改该程序以在所选文件夹的子文件夹中搜索txt文件吗?
,看一下[提高文件系统(http://www.boost.org/doc/libs/1_56_0/libs/filesystem/doc/tutorial。 HTML) – 2014-10-17 08:50:22