Flushing a stream
suggest changeFile streams are buffered by default, as are many other types of streams. This means that writes to the stream may not cause the underlying file to change immediately. In order to force all buffered writes to take place immediately, you can flush the stream. You can do this either directly by invoking the flush() method or through the std::flush stream manipulator:
std::ofstream os("foo.txt");
os << "Hello World!" << std::flush;
char data[] = "Foo";
os.write(data, 3);
os.flush();
There is a stream manipulator std::endl that combines writing a newline with flushing the stream:
// Both following lines do the same thing
os << "Hello World!\n" << std::flush;
os << "Hello World!" << std::endl;
Buffering improves throughput, so avoid unnecessary flushing in write-heavy code. Flush when another process or device must observe the data immediately, or before an operation whose correctness depends on the write being complete. Closing a healthy output stream flushes its buffer automatically.