0

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.

Vertexwahn
  • 7,709
  • 6
  • 64
  • 90

1 Answers1

3

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.

Ron
  • 14,674
  • 4
  • 34
  • 47
  • 1
    C++ 17 introduces a [cross-platform filesystem API](http://en.cppreference.com/w/cpp/filesystem), so OP might be able to avoid the OS specific API. – hnefatl Jan 26 '18 at 17:54
  • 1
    I think the first solution is the best if you have some "holes" in the employee numbers, because it will avoid a lot of attempts to open not existing files. The second is the best if the numbers are contiguous. – Benjamin Barrois Jan 26 '18 at 17:56
  • The simplest way is with the `for (size_t i = 0; i < 4000; i++)` loop – Charles-François St-Cyr Jan 26 '18 at 17:56