setbuf()

Updated: April 19, 2023

Associate a buffer with a stream

Synopsis:

#include <stdio.h>

void setbuf( FILE *fp, 
             char *buffer );

Arguments:

fp
The stream that you want to associate with a buffer.
buffer
NULL, or a pointer to the buffer; see below.

Library:

libc

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

Description:

The setbuf() function associates the supplied buffer with the stream specified by fp. If you want to call setbuf(), you must call it after opening the stream, but before doing any reading, writing, or seeking.

If buffer is NULL, all input/output for the stream is completely unbuffered. If buffer isn't NULL, then it must point to an array that's at least BUFSIZ characters long, and all input/output is fully buffered.

Note:
  • The setbuf() function doesn't have a way to notify you if an error occurred; you should use setvbuf() instead.
  • (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().

Examples:

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
    char *buffer;
    FILE *fp;

    buffer = (char *)malloc( BUFSIZ );
    if( buffer == NULL ) {
        return EXIT_FAILURE;
    }

    fp = fopen( "some_file", "r" );

    setbuf( fp, buffer );

    /* . */
    /* . */
    /* . */

    fclose( fp );

    free( buffer );

    return EXIT_SUCCESS;
}

Classification:

ANSI, POSIX 1003.1

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