• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 299
  • Last Modified:

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
0
DJ_AM_Juicebox
Asked:
DJ_AM_Juicebox
  • 2
1 Solution
 
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
 
jasonclarkeCommented:
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:

Thanks Jason,

I should have mentioned that.  :(

Betcha that solves the need.   :)


Kent
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now