c++ - ifstream 读取所有以开头的文件

标签 c++ file ifstream

我有多个以 employee_ 开头的文件

Examples : 
  employee_2053.txt
  employee_1284.txt
  employee_4302.txt
  etc...

我想要的是读取每个文件的内容。我试过这样的事情:

string fname, lname;

ifstream file("employee_" + *);
while(file>>fname>>lname) {
    // Do something here that is gonna be repeated for every file
}

我在 "employee_"+ * 处出错。当我考虑它时,它不起作用是有道理的。我想我需要一个循环或其他东西,我只是不知道该怎么做。

最佳答案

使用特定于操作系统的 API 枚举可用文件并将名称存储在容器中,例如字符串 vector std::vector<std::string> v; .遍历容器:

for (auto el : v) {
    std::ifstream file(el);
    // the code
}

如果您确定存在具有基于范围的硬编码值的现有文件,您可以使用 std::to_string for 中的函数循环:

for (size_t i = 0; i < 4000; i++) {
    std::ifstream file("employee_" + std::to_string(i) + ".txt");
    // the code
}

更新:
正如评论中指出的那样,OS API 的替代方案是 file system。支持 C++17 标准和 Boost Filesystem Library .

关于c++ - ifstream 读取所有以开头的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48466627/

相关文章:

c++ - TinyXml Unresolved external 问题

java - 当用户使用 java servlet 上传文件时,如何找到文件的内容类型?

c# - 是否可以使用 .NET 跟踪文件操作?

c++ - 程序应何时通知用户它无法打开文件?

c++ - 有效地从文件的各个行中读取 token

c++ - STL 集中的指针委托(delegate)

C++ 返回临时对象的问题

c++ - 有没有办法从集合中删除并将值移动到临时值?

delphi - 即使仅与 faDirectory 一起使用,FindNext 也会返回文件名

c++ - ifstream 获取下一个字符