Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In simple terms, what is the purpose of flush() in ostream

By definition taken from: http://www.cplusplus.com/reference/iostream/ostream/flush/ , it is not clear why the function exists, and for what purpose you would use it for. Why not call flush(), every time your write to the stream?

like image 790
umps Avatar asked Sep 09 '12 02:09

umps


People also ask

What does Ostream flush do?

The std::ostream::flush() function technically calls std::streambuf::pubsync() on the stream buffer (if any) which is associated with the stream: The stream buffer is responsible for buffering characters and sending characters to the external destination when the used buffer would overflow or when the internal ...

What is flush () in Java?

The flush() method of PrintWriter Class in Java is used to flush the stream. By flushing the stream, it means to clear the stream of any element that may be or maybe not inside the stream. It neither accepts any parameter nor returns any value. Syntax: public void flush()

What does flush mean in programming?

To flush, means to empty the buffer. Now, buffer is temporary storage area for storing data. Both endl and \n can be used to print newline character but there is minor difference between these two : In case of endl, buffer is cleared by usage of internal call to flush the buffer.

What are flush () and close () used for?

flush() writes the content of the buffer to the destination and makes the buffer empty for further data to store but it does not closes the stream permanently. That means you can still write some more data to the stream. But close() closes the stream permanently.


1 Answers

In all likelihood, the word flush comes from exactly what you'd flush in real-life. A toilet...

So let's try a toilet analogy:

Flushing every time a new one drops into the bowl is very time-consuming and a complete waste of water. That's a big problem today where everyone's trying to be environmentally friendly.

So what do you do instead? You buffer it by saving it all up and flushing once at the end. If for whatever reason, you can always "prematurely" flush somewhere in the middle when you're not done.


C++ streams (among other things) work much the same way. To reduce overhead and improve performance, a stream buffers its contents and only periodically "flushes" it. The draw-back of this is that you may get "delayed" behavior like in this question: Why does printf not flush after the call unless a newline is in the format string?

So that's what flush() is for. To allow you to override the buffering.

like image 171
Mysticial Avatar answered Oct 14 '22 23:10

Mysticial