setbuffer()

Updated: October 28, 2024

Assign block buffering to a stream

Synopsis:

#include <unix.h>

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

Arguments:

iop
The stream that you want to set the buffering for.
abuf
NULL, or a pointer to the buffer that you want the stream to use.
asize
The size of the buffer.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

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.

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

If you want to use setbuffer(), you must call it after opening the stream, but before doing any reading, writing, or seeking. 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, specifies the default size:

char buf[BUFSIZ];
Note: (QNX Neutrino 6.6 or later) As a QNX Neutrino extension, you can use the STDIO_DEFAULT_BUFSIZE environment variable to override BUFSIZ as the default buffer size for stream I/O. The value of STDIO_DEFAULT_BUFSIZE must be greater than that of BUFSIZ. For more information, see Adjusting the buffer size in the entry for fopen().

You can use freopen(). to change a stream from unbuffered or line-buffered to block buffered. To change a stream from block-buffered or line-buffered to unbuffered, call freopen(), and then call setvbuf() 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.

  翻译: