【发布时间】:2014-10-17 08:41:31
【问题描述】:
我正在尝试从一个文件夹中读取所有 txt 文件,包括使用 C++ 从所选文件夹的子目录中读取的 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文件?
【问题讨论】: