c++filefor-loopwhile-loopfstream

Why is the "for" cycle not creating multiple files?


Why is this code not creating several files? ofstream should create a file when it encounters a file name that doesn't exist. However, for some reason, even though the names are different, it creates only one.

#include <iostream>
#include <fstream>
using namespace std;

int main(void){
    ofstream fout;
    for (int a = 0; a <= 2; a++){
        string name = "test" + to_string(a) + ".txt";
        fout.open(name);
    }
    return 0;
}

Tried switching from "for" to "while" like this

#include <iostream>
#include <fstream>
using namespace std;

int main(void){
    ofstream fout;
  int a = 0;
  while (a <= 2){
    string name = "test" + to_string(a) + to_string(a+1) + ".txt";
    fout.open(name);
    a++;
  }

    return 0;
}

but no result. Also I added another number (a+1) to the name and still got the same result with one created file


Solution

  • You are opening the ofstream but not closing it. the open() method will fail if the stream is already open.

    Try this:

    ofstream fout;
    for (int a = 0; a <= 2; a++){
        string name = "test" + to_string(a) + ".txt";
        fout.open(name);
        fout.close(); // <-- add this!
    }
    

    A better option is to simply move the ofstream object inside the loop so it is created and destroyed on each iteration:

    for (int a = 0; a <= 2; a++){
        string name = "test" + to_string(a) + ".txt";
        ofstream fout(name);
    }