I have multiple files that start with employee_
Examples :
employee_2053.txt
employee_1284.txt
employee_4302.txt
etc...
What I want is to read the content of every file. I tried something like this:
string fname, lname;
ifstream file("employee_" + *);
while(file>>fname>>lname) {
// Do something here that is gonna be repeated for every file
}
I have an error at "employee_" + *
. When I think about it, it makes sense that it doesn't work. I guess I will need a loop or something, I just don't know how to do it.
Enumerate the available files using the OS specific API and store the names inside a container such as vector of strings std::vector<std::string> v;
. Iterate over a container:
for (auto el : v) {
std::ifstream file(el);
// the code
}
If you know for sure there are existing files with range based hard coded values you can utilize the std::to_string function inside a for
loop:
for (size_t i = 0; i < 4000; i++) {
std::ifstream file("employee_" + std::to_string(i) + ".txt");
// the code
}
Update:
As pointed out in the comments the alternative to OS API is a file system support in the C++17 standard and the Boost Filesystem Library.