C++ 读取整个文件目录

C++ Reading an entire file directory

本文关键字:文件目录 读取 C++      更新时间:2023-10-16

我做了一个简短的程序,可以读取一定数量的文本文件,并从中提取一些有针对性的信息。但是,这依赖于我将所有这些文本文件添加到项目文件夹中,并单独重命名每个文本文件以赋予它们的名称一个模式。

我想让我的代码读取文件夹中的所有文件(由那里的路径命名(,无论名称和文件夹中的文件数量如何。

我是编程的初学者,所以如果所有步骤都尽可能简单地解释,我将不胜感激,这样我就可以从这个:)

谢谢!

您想在 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;
}