'Loop for load multiples files (C++)

I´m trying to load all the files in a folder that have names from the form "file_i.csv".

For this I write the program:

void load_reel_set()
{
    bool file_exists = true;
    unsigned n_files = 0;
    
    vector<unsigned> my_vector;
    string line;
    int i;

    ifstream file("..\\file_" + to_string(n_files) + ".csv");
    file_exists = file.good();

    
    while (file_exists) {

        //Load reel strips from file:
        my_vector.clear();

        getline(file, line, '\n');
        save_line(my_vector, line);

        all_my_vectors.push_back(my_vector);
        file.close();

        n_files++;
        ifstream file("..\\file_" + to_string(n_files) + ".csv");
        file_exists = file.good();
    }
}

The function "save_line" turns character to unsigned place by place and saves that in a vector.

I have four files in the folder, each with only one line. This function recognizes all my files but, after the first one, the lines for the files are empty. The "all_my_vectors" vector has the expected value in the first loop but is 0 for the next ones.



Solution 1:[1]

You have two independent instances ifstream file, the one inside the loop hiding the one outside. While the inner one runs out of scope after closing the loop the outer one remains at the end of the very first file.

Try instead:

file.open("the new path");

Side note: This file_exists variable is totally obsolete, you can simply check directly while(file.good()).

You actually can avoid a bit of duplicate code by:

// other variables...

for(unsigned int n_files = 0;; ++n_files)
{
    std::ifstream file("path to next file");
    if(!file)
    {
        break;
    }

    // now file content handling here
}

Note that now the std::ifstream is back inside the loop again, but there's now no outer instance hidden any more.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aconcagua