16.6 Buffering Problems
Buffered I/O does not write immediately to the file. Instead, the
data is kept in a buffer until there is enough for a big write, or
until the buffer is flushed. The following program is designed to
print a progress message as each section is finished.
std::cout << "Starting";
do_step_1( );
std::cout << "Step 1 complete";
do_step_2( );
std::cout << "Step 2 complete";
do_step_3( );
std::cout << "Step 3 complete\n";
Instead of writing the messages as each step completes,
std::cout puts them in a buffer. Only after the
program is finished does the buffer get flushed, and all the messages
come spilling out at once.
The
I/O manipulator std::flush forces the flushing of
the buffers. Properly written, the above example should be:
std::cout << "Starting" << std::flush;
do_step_1( );
std::cout << "Step 1 complete" << std::flush;
do_step_2( );
std::cout << "Step 2 complete" << std::flush;
do_step_3( );
std::cout << "Step 3 complete\n" << std::flush;
Because each output statement ends with a
std::flush, the output is displayed immediately.
This means that our progress messages come out on time.
 |
The C++ I/O classes buffer all output. Output to
std::cout and std::cerr is line
buffered. In other words, each newline forces a buffer flush. Also,
C++ is smart enough to know that std::cout and
std::cerr are related to
std::cin and will automatically flush these two
output streams just before reading std::cin. This
makes it possible to write prompts without having to worry about
buffering:
std::cout << "Enter a value: "; // Note: No flush
std::cin >> value;
|
|
|