如何读取文件夹中的所有txt文件? (包括子文件夹)
问题描述:
我正在尝试从文件夹中读取所有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文件吗?
答
我在这里找到一种方法来检查文件是否是一个目录:Accessing Directories in C
你应该做的首先是把你的代码的函数里面,可以说,无效F(字符*目录),从而使您可以处理多个文件夹。然后使用上述链接中提供的代码来查找文件是否是目录。
如果它是一个目录,请调用f,如果它是一个txt文件,请执行你想要的操作。
要小心一件事:每个目录中都有一些目录会将您发送到无限循环。 “”指向你的当前目录,“..”指向父目录,“〜”指向主目录。你可能想要排除这些。 http://en.wikipedia.org/wiki/Path_%28computing%29
答
最简单的方法是编写一个read_one_file()函数,并递归调用它。
read_one_file()看起来是这样的:
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 */
}
}
,看一下[提高文件系统(http://www.boost.org/doc/libs/1_56_0/libs/filesystem/doc/tutorial。 HTML) – 2014-10-17 08:50:22