C++ 读取整个文件目录
C++ Reading an entire file directory
我做了一个简短的程序,可以读取一定数量的文本文件,并从中提取一些有针对性的信息。但是,这依赖于我将所有这些文本文件添加到项目文件夹中,并单独重命名每个文本文件以赋予它们的名称一个模式。
我想让我的代码读取文件夹中的所有文件(由那里的路径命名(,无论名称和文件夹中的文件数量如何。
我是编程的初学者,所以如果所有步骤都尽可能简单地解释,我将不胜感激,这样我就可以从这个:)
谢谢!
您想在 C++17 标准库中使用std::filesystem::directory_iterator
。 一个最小的例子:
#include <filesystem>
#include <fstream>
int main()
{
for (auto& file : std::filesystem::directory_iterator{ "." }) //loop through the current folder
{
std::ifstream fs{ file.path() }; //open the file
//or because directory_entry is implicit converted to a path, so you can do
//std::ifstream fs{ file };
//... process the file
}
}
#include <iostream>
#include <dirent.h>
#include <fstream>
#include <sys/types.h>
using namespace std;
vector<string> list_dir(const char *path) {
vector<string> AllFilesName;
struct dirent *entry;
DIR *dir = opendir(path);
if (dir == NULL) {
return;
}
//readdir return a pointer to the entry of a folder (could be any type not only .txt)
while ((entry = readdir(dir)) != NULL) {
AllFilesName.push_back(entry->d_name);
//push the name of every file
}
closedir(dir);
return AllFilesName;
}
string readFile(string name){
ifstream inFile;
inFile.open("C:\temp\"+name);//concatenate the name with the directory path
//just replace your folder path with C:\temp
while(inFile >> x) {
//x is the content of the file do whatever you want
}
//return the contetn of the text
}
int main() {
vector<string> nameOfFiles = list_dir("/home/username/Documents");
for(int i=0;i<nameOfFiles.size();i++){
string contentOfTheFile = readFile(nameOfFiles[i]);//read the folder know as you like
}
return 0;
}
相关文章:
- 用c++从输入文件中读取另一行
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 如何在C++中从文件中读取/写入多个对象
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 如何从二进制文件中读取字符串
- 如何从dicom文件中读取二进制数据
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 我的程序没有从文件中读取并输入数据
- 如何从txt文件中读取多个不同长度的数组?
- 在一次迭代中从 txt 文件中读取多行
- 如何在我从C++文件中读取后立即删除行
- 从二进制文件中读取整数数组
- C++ 读取整个文件目录
- c++ GetPrivateProfileString 从当前目录读取 ini 文件
- 创建文件,读取目录更改问题
- 试图插入用户定义的对象到一个矢量,而我从文件目录读取值
- 如何在文件目录中读取