ifstream 读取所有以开头的文件
ifstream read every files that start with
我有多个以 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_" + *
有一个错误。当我考虑它时,它不起作用是有道理的。我想我需要一个循环或其他东西,我只是不知道该怎么做。
使用 OS 特定 API 枚举可用文件,并将名称存储在容器中,例如字符串向量 std::vector<std::string> v;
。遍历一个容器:
for (auto el : v) {
std::ifstream file(el);
// the code
}
如果您确定存在具有基于范围的硬编码值的现有文件,您可以在 for
循环中使用 std::to_string 函数:
for (size_t i = 0; i < 4000; i++) {
std::ifstream file("employee_" + std::to_string(i) + ".txt");
// the code
}
更新:
正如评论中指出的 OS API 的替代方法是 file system support in the C++17 standard and the Boost Filesystem Library.
我有多个以 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_" + *
有一个错误。当我考虑它时,它不起作用是有道理的。我想我需要一个循环或其他东西,我只是不知道该怎么做。
使用 OS 特定 API 枚举可用文件,并将名称存储在容器中,例如字符串向量 std::vector<std::string> v;
。遍历一个容器:
for (auto el : v) {
std::ifstream file(el);
// the code
}
如果您确定存在具有基于范围的硬编码值的现有文件,您可以在 for
循环中使用 std::to_string 函数:
for (size_t i = 0; i < 4000; i++) {
std::ifstream file("employee_" + std::to_string(i) + ".txt");
// the code
}
更新:
正如评论中指出的 OS API 的替代方法是 file system support in the C++17 standard and the Boost Filesystem Library.