5.9.4. Buffering

Both the stdio and iostream libraries use an idea called buffering for both input and output.


Output buffering

Disk operations are only efficient on large chunks of information. When you write to a file, the characters that you write are accumulated in a memory buffer (an array of characters) until either a large enough number of bytes have been accumulated or the program closes the file. Then the buffer is flushed, writing it out to the file.

Information written to a terminal is also accumulated in a buffer, but that buffer is normally flushed when a newline character is written.

That can be significant to you for the following reasons.

  1. Suppose that your program contains trace prints. You often direct trace prints to a file because there is too much information to write into a terminal. If your program encounters an error such as a memory fault, the program cannot flush the buffers, and any traces written into a buffer but not flushed are lost. You can be misled into thinking those trace prints did not occur.

    Even if you are writing traces to a terminal, any that do not end a line will not show up if an error occurs before the next end-of-line is written.

  2. The stdio and iostream libraries use different buffers. If you interleave prints to the standard output using those libraries, they will be stored in different buffers. If the standard output is redirected to a file you can get very surprising results.

You can force an output buffer to be flushed. Use the following.

fflush(f)

Flush FILE* value f (stdio library).

fflush(stdout)

Flush the standard output (stdio library).

out.flush()

Flush outfile out (iostream library).

cout.flush()

Flush the standard output (iostream library).


Input buffering

Input from a file is read in large chunks and stored in a memory buffer. When you do a read operation, you actually get information from that memory buffer, until it is empty, when another chunk of data is read from the disk.

That is normally not a problem. It can be a serious problem when you try to read information using both the iostream and the stdio libraries. They use different buffers.