0

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

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

3

You have to close the stream before you can open another one.

fout.open(name); will fail and return immediately if the stream is already open.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.