ofstream, when is data written?

Hi,

If i open a stream to a text file, when is the data actually writen to the file and viewable by another process? Example:

int main()
{
    ofstream o("C:\\test.txt");

    o << "hello" << endl;

    // pause...

    o << "world" << endl;
}

If i take the text file and open it after the writing of "hello" with notepad, will I see "hello" in the text file, or will nothing be written until the file is closed when main() exits?

Thanks
DJ_AM_JuiceboxAsked:
Who is Participating?
 
jasonclarkeConnect With a Mentor Commented:
You can force the stream to send it's content to the file with a call to flush...

ofstream o("C:\\test.txt");

    o << "hello" << endl;
    o.flush();  // should make sure everything is in the file...

    // pause...

    o << "world" << endl;
    o.flush();
0
 
Kent OlsenData Warehouse Architect / DBACommented:
Hi DJ,

That's somewhat dependent on the implementation.  Streams are buffered but there is no standard that dictates how large the buffer is so there is no way to predict when the buffer will flush.

When writing to a stream that you create, the behavior is clearly at the mercy of the implementation.  Writing to stdout will probably have the same behavior as writing to a stream that you create.

When writing to stderr, output is buffered, but the buffer is flushed with every write (or every newline, I don't recall).


Good Luck,
Kent
0
 
Kent OlsenData Warehouse Architect / DBACommented:

Thanks Jason,

I should have mentioned that.  :(

Betcha that solves the need.   :)


Kent
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.