[Previous] [Contents] [Index] [Next]

setbuffer()

Assign block buffering to a stream

Synopsis:

#include <unix.h>

void setbuffer( FILE *iop,
                char *abuf,
                size_t asize );

Library:

libc

Description:

The setbuffer() and setlinebuf() functions assign buffering to a stream. The types of buffering available are:

Unbuffered
Information appears on the destination file or terminal as soon as written.
Block buffered
Many characters are saved and written as a block.
Line buffered
Characters are saved until either a newline is encountered or input is read from stdin.

The fflush() function may be used to force the block out early. Normally all files are block buffered. A buffer is obtained from malloc() when the first getc() or putc() is performed on the file. If the standard stream stdout refers to a terminal, it's line buffered. The standard stream stderr is unbuffered by default.

The setbuffer() function can be used after a stream iop has been opened but before it's read or written. It uses the character array abuf, whose size is given by asize, instead of an automatically allocated buffer. If abuf is NULL, input and output are completely unbuffered. A manifest constant BUFSIZ, defined in the <stdio.h> header, tells how large an array is needed:

char buf[BUFSIZ];

A stream can be changed from unbuffered or line buffered to block buffered by using freopen(). A stream can be changed from block buffered or line buffered to unbuffered by using freopen() followed by setbuf() with a buffer argument of NULL.

Classification:

Unix

Safety:
Cancellation point No
Interrupt handler No
Signal handler No
Thread Yes

Caveats:

A common source of error is allocating buffer space as an automatic variable in a code block, and then failing to close the stream in the same block.

See also:

fclose(), fflush(), fopen(), fread(), freopen(), getc(), malloc(), printf(), putc(), puts(), setbuf(), setlinebuf(), setvbuf()


[Previous] [Contents] [Index] [Next]