What is setvbuf in C?

setvbuf is a C library function that defines how a stream is buffered according to the mode provided in the function’s argument.

Syntax

int setvbuf(FILE *stream, char *buffer, int mode, size_t size)

Parameters

  • stream is the pointer to a file object to which the buffer is set.
  • buffer is a pointer to the user allocated buffer. If set to null, the function automatically allocates the buffer of the size provided.
  • mode is the buffering mode to use. They are listed down below:
Mode Description
_IOFBF Full Buffering - Data is written to output once the buffer is full. The buffer accepts input when it is empty, and an input operation is requested.
_IOLBF Line Buffering - Data is written on output when a newline is inserted in the stream or the buffer gets full. The buffer accepts input till the next newline when it is empty, and an input operation is requested.
_IONBF No Buffering - No buffer is used. I/O operations are written as they arrive. buffer and size parameters are ignored.
  • size is the buffer size in bytes.

Return value

The function returns 0 on success and a non-zero value on failure.

Example

A file called myFile.txt is made in the program below, and a buffer of 1024 bytes is requested for the file’s stream. As shown in line 10, we have used a full buffer which means that the output to this stream is only written to the file once the buffer is full:

#include<stdio.h>
#include <string.h>
int main() {
char buffer[1024];
char readBuffer[1024];
memset( buffer, '\0', sizeof( buffer )); //Initializing the buffer
FILE *pFile;
pFile = fopen("myFile.txt","w");
setvbuf( pFile , buffer , _IOFBF , 1024 );
// File operations here
if (pFile == NULL) {
printf("Error!");
}
fprintf(pFile, "%s","HelloWorld!");
fclose (pFile);
pFile = fopen("myFile.txt", "r");
if (pFile == NULL) {
printf("File does not exist.\n");
}
fscanf(pFile, "%s", &readBuffer);
printf("File contains the following strings: %s", readBuffer);
return(0);
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved