首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++读取整个文件目录

问C++读取整个文件目录
EN

Stack Overflow用户
提问于 2020-06-21 23:28:08
回答 2查看 1.7K关注 0票数 0

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

我想让我的代码读取一个文件夹中的所有文件(由那里的路径命名),而不管名称和文件夹中的文件量。

我完全是编程的初学者,所以如果所有步骤都尽可能简单地解释一下,我会非常感激,这样我就可以从中学到东西:)

非常感谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-06-21 23:57:11

您希望在C++17标准库中使用std::filesystem::directory_iterator。一个最小的例子:

代码语言:javascript
复制
#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
    }
}
票数 3
EN

Stack Overflow用户

发布于 2020-06-22 00:32:14

代码语言:javascript
复制
#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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62500676

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档