2

I have a file that need to be open multiple times during the runtime. Each time some text are appendedd into the file. Here is the code:

    ofstream fs;
    fs.open(debugfile, fstream::app);
    ostream_iterator<double> output(fs, " ");
    copy(starting_point.begin(), starting_point.end(), output);
    ...
    fs.open(debugfile, fstream::app);
    ostream_iterator<double> output1(fs, " ");
    copy(starting_point.begin(), starting_point.end(), output1);

My question is can I use one stream iterator "output" every time I open the file, e.g. some way to clean it?

Thanks

colddie
  • 1,029
  • 1
  • 15
  • 28

2 Answers2

1

You may use the following code:

ofstream fs;
fs.open(debugfile, fstream::app);
ostream_iterator<double> output(fs, " ");
copy(starting_point.begin(), starting_point.end(), output);
...
fs.open(debugfile, fstream::app);
output = ostream_iterator<double>(fs, " ");
copy(starting_point.begin(), starting_point.end(), output1);

Here the same variable output is used to store the iterator, but the iterator itself is created from scratch and assigned to this variable using operator =.

alexeykuzmin0
  • 6,344
  • 2
  • 28
  • 51
0

For me, there is nothing to do (appart reassign value) for your problem.

Just don't forget to close and clear your stream before re-open it :

std::ofstream file("1");
// ...
file.close();
file.clear(); // clear flags
file.open("2");

from : C++ can I reuse fstream to open and write multiple files?

Community
  • 1
  • 1
baddger964
  • 1,199
  • 9
  • 18