Question

Is there a way to reset an ofstream back to the beginning of the stream but not write over the data? I know how to reset the stream to the beginning but then it writes over all of the old data. I realize I could just save the initial data until I'm ready to write it but it is a very large amount that I'm not sure will store very well. Another option I suppose is to create a temp file with my initial large data, write my new data in the actual file then copy the temp file over and erase it. I suppose I'm just looking for something a little more convenient then those two if possible. Changing the way I get the data isn't an option unfortunately. With this code:

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, const char * argv[])
{
    ofstream out_stream("~/Desktop/test_out.txt");
    out_stream <<
    "This is some test file\n" <<
    "I want to reset stream\n" <<
    "Start working......now\n";

    out_stream.seekp(0, ios_base::beg);//this sets to beginning but erases old data

    out_stream <<
    "I hope this workssssss\n";

    out_stream.close();
    return 0;
}

I would want this output:

I hope this workssssss
This is some test file
I want to reset stream
Start working......now
Was it helpful?

Solution

You seem to want to "prepend" text to the file. That's just not possible. The new text will overwrite what is already there.

You'll have to write the new text to a new file and then write the text from the original file to the new file afterwards.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top