C Standard Library

C <stdio.h> - setbuf() Function



The C <stdio.h> setbuf() function is used to control the buffering for the specified stream. If buffer is a null pointer, buffering is disabled for the stream and the stream is unbuffered. If buffer is not a null pointer, then the buffer must point to a character array of at least BUFSIZ bytes in size.

This function should be called after the stream pointed to by stream is associated with an open file but before any input or output operation is performed on the stream.

Syntax

int setbuf (FILE * stream, char * buffer);

Parameters

stream Specify a pointer to a FILE object that identifies an open stream.
buffer Specify pointer to a buffer for the stream to use or null pointer to turn off the buffer.

Return Value

None.

Example:

The example below describes the usage of setbuf() function.

#include <stdio.h>

int main() {
  char buf[50];

  setbuf(stdout, buf);
  printf("Hello"); //The buffer contains "Hello" 
  //but nothing is written to stdout yet
  fflush(stdout);  //Now "Hello" is written to stdout

  setbuf(stdout, NULL);
  printf(" World!"); //" World!" is written to stdout
  //there is no buffering

  return 0;
}

The output of the above code will be:

Hello World!

❮ C <stdio.h> Library

5