setvbuf() Function

The setvbuf() function in C stdio.h allows you to change the buffering behavior of a stream by specifying a custom buffer, its mode, and size. It plays an essential role in controlling how data is temporarily stored between I/O operations and the physical file, which can help optimize performance or disable buffering when necessary.


Syntax of setvbuf()

</>
Copy
int setvbuf(FILE *stream, char *buffer, int mode, size_t size);

Parameters

ParameterDescription
streamA pointer to a FILE object associated with an open file.
bufferA pointer to a user-allocated array to be used as a buffer. If set to a null pointer, a buffer is automatically allocated.
modeAn integer that specifies the buffering mode. Typically one of the following macros:
_IOFBF – Full buffering
_IOLBF – Line buffering
_IONBF – No buffering
sizeThe size of the buffer in bytes. This value is used as a hint if a buffer is automatically allocated.

This function must be called after the stream is opened but before any input or output operations are performed on it. The buffering mode directly affects how and when data is transmitted between the program and the file, and improper use can lead to performance issues or unexpected behavior.


Return Value

If the buffer is successfully assigned to the file stream, setvbuf() returns 0. Otherwise, a non-zero value is returned, indicating an error, such as an invalid mode or a failure in buffer allocation.


Examples for setvbuf()

Example 1: Using a User-Allocated Buffer for Full Buffering

This example demonstrates how to use setvbuf() to assign a user-allocated buffer for full buffering on a file stream.

Program

</>
Copy
#include <stdio.h>

int main() {
    FILE *fp = fopen("example.txt", "w");
    char myBuffer[1024];

    if (fp == NULL) {
        perror("Error opening file");
        return 1;
    }

    // Set full buffering with a user-allocated buffer
    if (setvbuf(fp, myBuffer, _IOFBF, sizeof(myBuffer)) != 0) {
        perror("Failed to set buffer");
        return 1;
    }

    fprintf(fp, "This is an example using a user-allocated buffer.");
    fclose(fp);
    return 0;
}

Explanation:

  1. The program opens a file example.txt for writing.
  2. A user-allocated buffer myBuffer of 1024 bytes is defined.
  3. setvbuf() is called to set the stream to full buffering using the provided buffer.
  4. The program writes a message to the file and closes it, flushing the buffer to disk.

Program Output:

(No console output; the result is written to "example.txt")

Example 2: Disabling Buffering for a Stream

This example shows how to disable buffering on a stream by using _IONBF with setvbuf().

Program

</>
Copy
#include <stdio.h>

int main() {
    FILE *fp = fopen("nobuf.txt", "w");

    if (fp == NULL) {
        perror("Error opening file");
        return 1;
    }

    // Disable buffering for the file stream
    if (setvbuf(fp, NULL, _IONBF, 0) != 0) {
        perror("Failed to disable buffering");
        return 1;
    }

    fprintf(fp, "Buffering is disabled for this stream.");
    fclose(fp);
    return 0;
}

Explanation:

  1. The file nobuf.txt is opened for writing.
  2. setvbuf() is called with a null pointer and mode _IONBF to disable buffering.
  3. Data written to the file is immediately flushed without being stored in an intermediate buffer.
  4. The file is closed after writing, ensuring that all output has been processed.

Program Output:

(No console output; the result is written to "nobuf.txt")

Example 3: Using Automatic Buffer Allocation

This example illustrates how setvbuf() automatically allocates a buffer when a null pointer is provided.

Program

</>
Copy
#include <stdio.h>

int main() {
    FILE *fp = fopen("auto_buffer.txt", "w");

    if (fp == NULL) {
        perror("Error opening file");
        return 1;
    }

    // Automatically allocate a buffer for the stream using the provided size hint
    if (setvbuf(fp, NULL, _IOFBF, 2048) != 0) {
        perror("Failed to set automatic buffer");
        return 1;
    }

    fprintf(fp, "This file uses an automatically allocated buffer.");
    fclose(fp);
    return 0;
}

Explanation:

  1. The file auto_buffer.txt is opened for writing.
  2. setvbuf() is called with a null pointer, prompting the function to automatically allocate a buffer of 2048 bytes.
  3. The stream is set to full buffering mode, and output is stored in the allocated buffer until it is flushed.
  4. The file is closed, ensuring the buffer is flushed and all data is written to disk.

Program Output:

(No console output; the result is written to "auto_buffer.txt")