What does buffer flushing mean?

I am learning C ++ and I found something that I cannot understand:

Output buffers can be explicitly flushed to force the buffer to be written. By default reading cin flushes cout ; cout also cleared when the program ends normally.

So flashing the buffer (for example, the output buffer): does it clear the buffer by deleting everything in it or by clearing the buffer, putting everything in it? Or does flushing a buffer mean something completely different?

+67
c ++ input output buffer flush
Feb 23 '13 at 16:38
source share
3 answers

Consider writing to a file. This is an expensive operation. If you write one byte at a time in your code, then each byte record will be very expensive. Thus, a common way to improve performance is to store the data you write in a temporary buffer. Only if there is a lot of data is the buffer written to the file. By delaying recordings and recording a large block at a time, performance improves.

With this in mind, flushing the buffer is an act of transferring data from the buffer to the file.

Does this buffer clear by deleting everything in it or by clearing the buffer, putting everything into it?

Last.

+85
Feb 23 '13 at 16:42
source share

You quoted the answer:

Output buffers can be explicitly flushed to cause the buffer to be written.

That is, you may need to "clear" the output to make it be written to the base stream (which may be a file or terminal in the examples given).

Normally stdout / cout is buffered by a line: the output is not sent to the OS until you write a new line or explicitly clear the buffer. The advantage is that something like std::cout << "Mouse moved (" << px << ", " << py << ")" << endl calls only one entry in the base "file" instead six, which is much better for performance. The disadvantage is that such a code:

 for (int i = 0; i < 5; i++) { std::cout << "."; sleep(1); // or something similar } std::cout << "\n"; 

will output ..... immediately (for an accurate implementation of sleep , see this question ). In such cases, you will need an extra << std::flush to ensure output is displayed.

Reading the cin dumps therefore you do not need an explicit reset for this:

 std::string colour; std::cout << "Enter your favourite colour: "; std::cin >> colour; 
+16
Feb 23 '13 at 16:50
source share

Clear the buffer, listing everything.

+3
Feb 23 '13 at 16:41
source share



All Articles