setbuf, setvbuf
Purpose
Assigns buffering to a stream.
Library
Standard I/O Library (libc.a)
Syntax
#include <stdio.h>
void setbuf (stream, buf)
FILE *stream;
char *buf;
int setvbuf (stream, buf, type, size)
FILE *stream;
char *buf;
int type, size;
Description
The setbuf subroutine causes the character array pointed
to by the buf parameter to be used instead of an automat-
ically allocated buffer. Use the setbuf subroutine after
a stream has been opened but before it is read or
written.
If the buf parameter is a NULL character pointer,
input/output is completely unbuffered.
A constant, BUFSIZ, defined in the stdio.h header file,
tells how large an array is needed:
char buf[BUFSIZ|;
For the setvbuf subroutine, type determines how stream
is buffered:
_IOFBF Causes input/output to be fully buffered.
_IOLBF Causes output to be line buffered. The
buffer is flushed when a new line is
written, the buffer is full, or input is
requested.
_IONBUF Causes input/output to be completely unbuf-
fered.
If the buf parameter is not a NULL character pointer,
the array it points to is used for buffering instead
of an automatically allocated buffer. The size param-
eter specifies the size of the buffer to be used. The
constant BUFSIZ in stdio.h can be a good buffer size.
If input/output is unbuffered, buf and size are
ignored.
A buffer is normally obtained from the malloc subroutine
at the time of the first getc or putc on the file, except
that the standard error stream, stderr, is normally not
buffered.
Output streams directed to terminals are always either
line-buffered or unbuffered.
Note: 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.
Related Information
In this book: "fopen, freopen, fdopen," "getc, fgetc,
getchar, getw," "malloc, free, realloc, calloc," "putc,
putchar, fputc, putw," "setbuffer, setlinebuf," and
"standard i/o library."