seb
seb

Reputation: 313

Re-use the same ofstream object

I would like to know if its possible to open multiple files with the same ofstream object ?

string fileName = "transaction" + to_string(nbFile) + ex;
ofstream fs(fileName.c_str());
fs << "foo";

nbFile++;
fs.close();

string fileName = "transaction" + to_string(nbFile) + ex;
ofstream fs(fileName.c_str());
fs << "foo2"

If I execute this code, the second file will to be create. I can't find in the MSDN doc if we can re-open a file using the same ofstream.

Upvotes: 0

Views: 192

Answers (2)

shauryachats
shauryachats

Reputation: 10405

You could always use the open() function of ofstream class.

fs.open(fileName.c_str());

Upvotes: 1

R Sahu
R Sahu

Reputation: 206717

I would like to know if its possible to open multiple files with the same ofstream object ?

Yes. Here's how:

string fileName = "transaction" + to_string(nbFile) + ex;
ofstream fs(fileName.c_str());
fs << "foo";

nbFile++;
fs.close();

fileName = "transaction" + to_string(nbFile) + ex;

// Not this.
// ofstream fs(fileName.c_str());

// This
fs.open(fileName.c_str());

fs << "foo2"

Upvotes: 2

Related Questions