But when I close the file or the buffer is full, the associated stream buffer is automatically synchronized, so why would I use the flush?
Would any example where it is advantageous to use the flush or endl?
One place Windows users are well familiar with is just before system("pause");, if you don't flush/endl the last output before that statement, "Press ENTER to continue" will be printed by pause.exe, while your output would still be waiting for the flush.
In general, flushing an output stream is expensive; and we would want to avoid fortuitous flushing (for instance with wanton use of std::endl).
There are a few cases where flushing a stream is a good idea.
A typical scenario is when we tie() two streams - we have an input stream and and output stream associated with the same physical device, and we need to synchronize the two stream buffers. Or we are appending to the same physical file via two different output steams. http://stdcxx.apache.org/doc/stdlibug/35-4.html
Another is when we want to create an audit trail, which must be complete and consistent even if our program terminates abnormally. (Typically, we use the format flag std::ios_base::unitbuf. See http://stdcxx.apache.org/doc/stdlibug/35-3.html)