C Library - setvbuf() function



The C library setvbuf() function is used to control the buffering of a file stream. This function can set the buffering mode and optionally specify a buffer for the stream.

Syntax

Following is the C library syntax of the setvbuf() function −

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

Parameters

This function accepts the following parameters −

  • stream: A pointer to a FILE object that identifies an open file stream.
  • buffer: A pointer to a character array that will be used as the buffer. If buffer is NULL, the function will allocate a buffer automatically.
  • mode: An integer that specifies the buffering mode. It can be one of the following
    • _IOFBF: Full buffering. Data is written when the buffer is full.
    • _IOLBF: Line buffering. Data is written when a newline character is encountered.
    • _IONBF: No buffering. Data is written immediately.
  • size: The size of the buffer in bytes. This parameter is ignored if buffer is NULL.

Return Value

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

Example 1: Full Buffering with Custom Buffer

Here, we set a custom buffer of size 1024 bytes for full buffering. Data is written to the file when the buffer is full or the file is closed.

Below is the illustration of the C library setvbuf() function.

#include <stdio.h>

int main() {
   FILE *file = fopen("example1.txt", "w");
   if (!file) {
       perror("Failed to open file");
       return 1;
   }

   char buffer[1024];
   if (setvbuf(file, buffer, _IOFBF, sizeof(buffer)) != 0) {
       perror("Failed to set buffer");
       return 1;
   }

   fputs("This is a test string.", file);
   fclose(file);
   return 0;
}

Output

The above code writes "This is a test string." to example1.txt when the file is closed.−

This is a test string.

Example 2: No Buffering

Thie example disables buffering, meaning data is written to the file immediately.

#include <stdio.h>

int main() {
   FILE *file = fopen("example3.txt", "w");
   if (!file) {
       perror("Failed to open file");
       return 1;
   }

   if (setvbuf(file, NULL, _IONBF, 0) != 0) {
       perror("Failed to set buffer");
       return 1;
   }

   fputs("This is a test string.", file);
   fputs("This is another string.", file);
   fclose(file);
   return 0;
}

Output

After execution of above code,it writes "This is a test string.This is another string." to example3.txt immediately as each fputs call is made.−

This is a test string.This is another string.
Advertisements