What is the difference between flush() and sync() in regard to fstream buffers?
basic_ostream::flush This is a non-virtual function which writes uncommited changes to the underlying buffer. In case of error, it sets an error flag in the used stream object. This is because the return value is a reference to the stream itself, to allow chaining.
basic_filebuf::sync This is a virtual function which writes all pending changes to the underlying file and returns an error code to signal success or failure.
endl
This, when applied to an ostream
, writes an '\n'
to the stream and then calls flush
on that stream.
So, essentially: flush
is a more general function for any stream, whereas sync
is explicitly bound to a file. flush
is non-virtual, whereas sync
is virtual. This changes how they can be used via pointers (to base class) in the case of inheritance. Furthermore, they differ in how they report errors.
sync
is a member of input
streams, all unread characters are cleared from the buffer. flush
is a member of output
streams and buffered output is passed down to the kernel.