我做了一个简短的程序,可以读取一定数量的文本文件,并从中提取一些有针对性的信息。但是,这依赖于我将所有这些文本文件添加到项目文件夹中,并单独重命名每个文件,以便为它们的名称指定一个模式。
我想让我的代码读取一个文件夹中的所有文件(由那里的路径命名),而不管名称和文件夹中的文件量。
我完全是编程的初学者,所以如果所有步骤都尽可能简单地解释一下,我会非常感激,这样我就可以从中学到东西:)
非常感谢!
发布于 2020-06-21 23:57:11
您希望在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
}
}发布于 2020-06-22 00:32:14
#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;
}https://stackoverflow.com/questions/62500676
复制相似问题