Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 5.4 Buffering 147


Withsetbuf, we can turn buffering on or off. Toenable buffering,bufmust point
to a buffer of lengthBUFSIZ,aconstant defined in<stdio.h>.Normally,the stream is
then fully buffered, but some systems may set line buffering if the stream is associated
with a terminal device.To disable buffering, we setbuftoNULL.
Withsetvbuf, we specify exactly which type of buffering we want. This is done
with themodeargument:
_IOFBF fully buffered
_IOLBF line buffered
_IONBF unbuffered
If we specify an unbuffered stream, thebufandsizearguments areignored. If we
specify fully buffered or line buffered,bufandsizecan optionally specify a buffer and its
size. If the stream is buffered and buf is NULL,the standardI/O library will
automatically allocate its own buffer of the appropriate size for the stream. By
appropriate size, we mean the value specified by the constantBUFSIZ.
Some C library implementations use the value from thest_blksizemember of thestat
structure(see Section 4.2) to determine the optimal standardI/O buffer size. As we will see
later in this chapter,the GNU C library uses this method.
Figure5.1 summarizes the actions of these two functions and their various options.

Function mode buf Buffer and length Type of buffering
non-null userbufof lengthBUFSIZ fully buffered or line buffered
NULL (no buffer) unbuffered
setbuf

non-null userbufof lengthsize
NULL system buffer of appropriate length
_IOFBF fully buffered
non-null userbufof lengthsize
NULL system buffer of appropriate length
_IOLBF line buffered
_IONBF (ignored) (no buffer) unbuffered

setvbuf

Figure 5.1Summary of thesetbufandsetvbuffunctions

Be awarethat if we allocate a standardI/O buffer as an automatic variable within a
function, we have to close the stream beforereturning from the function. (We’ll discuss
this point further in Section 7.8.) Also, some implementations use part of the buffer for
internal bookkeeping, so the actual number of bytes of data that can be stored in the
buffer can be less thansize.Ingeneral, we should let the system choose the buffer size
and automatically allocate the buffer.When we do this, the standardI/O library
automatically releases the buffer when we close the stream.
At any time, we can force a stream to be flushed.
#include <stdio.h>
int fflush(FILE *fp);
Returns: 0 if OK,EOFon error
Thefflushfunction causes any unwritten data for the stream to be passed to the
kernel. Asaspecial case, iffpisNULL,fflushcauses all output streams to be flushed.
Free download pdf