setvbuf : <stdio.h> library function

The function int setvbuf(FILE *stream, char *buffer, int mode, size_t size); sets the buffer to be used by a stream for Input/Output operations. It also allows to specify the mode and size of the buffer. If buffer argument is NULL, the function automatically allocates a buffer of size bytes. The setvbuf function must be called once the file associated with the stream has already been opened, and before doing any input or output operation on stream.

Various modes of buffering

Constant Description
_IOFBF Full buffering: On output, data is written once the buffer is full (or flushed). On Input, the buffer is filled when an input operation is requested and the buffer is empty.
_IONBF No buffering: No buffer is used. Each I/O operation is performed directly on given stream.
_IOLBF Line buffering: On output, data is written either when a newline character is pushed into the stream or when the buffer is full(or flushed), whatever happens first. On Input, the buffer is filled up to the next newline character when an input operation is requested and the buffer is empty.

Function prototype of setvbuf

int setvbuf(FILE *stream, char *buffer, int mode, size_t size);
  • stream : A pointer to a FILE object which identifies a stream.
  • buffer : This is pointer to a memory block to be used as buffer for given stream. The size of this buffer must be at least BUFSIZ bytes.
  • mode : This is an integer representing the mode of buffering. It's value must be one of the three(_IOFBF, _IOLBF and _IONBF) macro constants defined in stdio header file.
  • size : This is the size of buffer in bytes.

Return value of setvbuf

On Success, this function returns zero otherwise in case of an error it returns a non-zero value.

C program to show the use of setvbuf function

The following program shows the use of setvbuf function to set buffer for stdout stream.

#include <stdio.h>

int main(){
   char buffer[500];

   memset(buffer, '\0', sizeof(buffer));
   setvbuf(stdout, buffer, _IOFBF, 500);

   fputs("This string will go in buffer\n", stdout);
   fflush(stdout);

   return(0);
}

Program Output
This string will go in buffer