### I/O Buffering

IBM C and C++ Compilers buffers stream I/O to increase the efficiency of system-level I/O. The following buffering modes are used:

Unbuffered
  Characters are transmitted as soon as possible. This mode is also called unit buffered.
Line buffered
  Characters are transmitted as a block when a new-line character is encountered or when the buffer is filled.
Fully buffered
  Characters are transmitted as a block when the buffer is filled.

The buffering mode specifies the manner in which the buffer is flushed, if a buffer exists. Streams are fully buffered by default unless they are connected to a character device such as the keyboard or an operating system pipe. Streams for character devices are line buffered.

Standard iostreams cerr, and wcerr are unbuffered, but clog and wclog are fully buffered.

Your programs should take advantage of buffering to increase the efficiency of system-level I/O. To ensure your output appears in the expected order and is complete, you may have to control the buffering explicitly. Programs that use C stream I/O can control buffering in the following ways:

- Call the fflush function to clear the buffer. If the last operation on the stream is a read operation, fflush discards the unread portion of the buffer. If the last operation on the stream is a write operation, fflush writes out the contents of the buffer.
- Call the fclose function to flush the buffer for a file and then close it.

If your program terminates normally, IBM C and C++ Compilers automatically closes all files and flushes all buffers. When a program ends abnormally, all files are closed but the buffers are not flushed.

You can change the buffering mode of a stream from within your code. You must do this before performing any operation on the file.

To ensure data is transmitted to external storage as soon as possible, use the setvbuf or setbuf function to set the buffering mode to unbuffered. Call these functions after the file is open and before performing read or write operations on the file. You can also use setvbuf and setbuf to control buffering in other ways; setvbuf is the more flexible of the two functions.

The default buffer size is 4096 bytes. To specify a different initial size for the buffer allocated for the stream, set the blksize parameter of the fopen function when you open the stream.

Disk caching performed by the operating system can also affect the time when characters are actually transferred to and from a physical disk.

Stream Processing