Notes on Buffering
Buffering
- When you use the standard I/O, sometimes the data is buffered before it is delivered to it's destination
- The purpose of buffering is to improve efficiency by reducing the number of read/write system calls
- 3 Types of buffering:
- Fully Buffered - I/O happens when the buffer is full
- Line Buffered - I/O happens when either a newline character is encountered, or the buffer becomes full
- Unbuffered - I/O happens immediately. No buffering is used.
- Flushing = the writing of a standard I/O buffer
- Buffers can be explicitly flushed by using the fflush system call
- By default,
- Standard error is always unbuffered
- All other streams are line buffered if they refer to a terminal device; otherwise they are fully buffered
setvbuf()
We can change the buffering by calling the following function:
#include <stdio.h>
/* Returns: 0 if OK, nonzero on error */
int setvbuf(FILE *fp, char *buf, int mode, size_t size);
The setvbuf
function must be called after the stream has been opened, but before
any other operation is performed on the stream. With setvbufwe specify exactly what
type of buffering we want. To enable buffering:
- mode can be either _IOFBF (for fully buffered) or _IOLBF (for line buffered)
- set buf and size to NULL (you can optionally use buf and size to explicitly specify the buffer and its size. See p.124)
To disable buffering:
- set mode to _IONBF (for unbuffered)
- set buf and size to NULL (these arguments get ignored)