setbuf() — Control Buffering
Format
#include <stdio.h>
void setbuf(FILE *, char *buffer);
Language Level
ANSI
Threadsafe
Yes
Description
If the operating system supports
user-defined buffers, setbuf()
controls
buffering for the specified stream. The setbuf()
function
only works in ILE C when
using the integrated file system. The stream pointer
must refer to an open file before any I/O or repositioning has been
done.
If the buffer argument is NULL,
the stream is unbuffered. If not, the buffer must
point to a character array of length BUFSIZ, which is the
buffer size that is defined in the <stdio.h> include
file. The system uses the buffer, which
you specify, for input/output buffering instead of the default system-allocated
buffer for the given stream. stdout
, stderr
, and stdin
do not
support user-defined buffers.
The setvbuf()
function
is more flexible than the setbuf()
function.
Return Value
There is no return value.
Example
setbuf()
function
to establish a buffer of length BUFSIZ. When string is
written to the stream, the buffer buf is used and contains
the string before it is flushed to the file. #include <stdio.h>
int main(void)
{
char buf[BUFSIZ];
char string[] = "hello world";
FILE *stream;
memset(buf,'\0',BUFSIZ); /* initialize buf to null characters */
stream = fopen("setbuf.dat", "wb");
setbuf(stream,buf); /* set up buffer */
fwrite(string, sizeof(string), 1, stream);
printf("%s\n",buf); /* string is found in buf now */
fclose(stream); /* buffer is flushed out to myfile.dat */
}