如何从文件夹中读取所有txt文件?(包括子文件夹)
How to read all txt files from a folder? (including subfolders)
我正在尝试使用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文件,我应该对此程序进行什么修改?
最简单的方法是编写一个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 */
}
}
我在这里找到了一种检查文件是否是目录的方法:访问C 中的目录
首先应该做的是将代码放入一个函数中,比如说void f(char*dir),这样就可以处理多个文件夹。然后使用上面链接中提供的代码来查找文件是否为目录。
如果它是一个目录,调用f,如果它是txt文件,做你想做的事
注意一件事:在每个目录中都有一些目录会将您发送到一个无限循环。"."指向当前目录,".."指向父目录,"~"指向主目录。你可能会想排除这些。http://en.wikipedia.org/wiki/Path_%28computing%29
相关文章:
- 如何将更多文件夹添加到c++include路径
- GetShortPathName在网络驱动器上使用中文文件夹时失败
- VS2017,C++包含目录与附加包含目录,子文件夹包含失败-但为什么
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 如何在文档文件夹中创建目录
- "assimp/config.h"找不到,但它在文件夹中
- C++入门 5 版:类消息和文件夹
- 我可以在 Arduino 的库文件夹之外安装库吗?
- 如何按文件扩展名引用文件夹中的文件
- 在QTreeView中仅显示共享驱动器和文件夹
- 加载与引用 .NET DLL 位于同一文件夹中的引用的 .NET DLL 时"Not found"异常
- 介子复制/安装头文件到输出目录并保持文件夹结构
- vcruntime.h 从 Windows 包含文件夹中丢失?
- 在文件夹迭代上实现 RAII
- 使用 Powershell 命令将 cpp 文件的文件夹编译为 GNU 的 g++
- 使文件夹中的所有文件可供所有项目(子目录)访问
- 无法使用 CMake 从其他文件夹添加源文件
- 如何在安卓工作室中将c ++头文件从一个文件夹导入到另一个文件夹?
- 对单元测试(googletest)和项目/文件夹/文件的混淆
- 设计文件夹/文件系统