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;
}