Course contentsShow
← C
Lesson 752 of 1,21910. Input and OutputFree lesson

Setting custom buffers with setvbuf

Setting custom buffers with setvbuf

What you'll learn: How to manually control how C manages memory buffers for file operations to optimize program performance.

The "Waiting Room" for Data

When you write data to a file using fprintf or fwrite, C doesn't usually send that data to the disk immediately. Disk hardware is slow, so C acts like a bus driver waiting for a bus to fill up with passengers before departing. This "waiting room" is a chunk of memory called a buffer.

By default, the C standard library manages this automatically. However, if you are writing a high-performance database or a real-time logger, you might want a bigger bus (a larger buffer) to reduce trips to the disk, or no bus at all (no buffering) so data is saved instantly in case of a crash.

Using setvbuf

The setvbuf function allows you to hand-pick the size and type of this buffer. It must be called after opening a file but before performing any input or output operations on it.

Here is the function signature: setvbuf(FILE *stream, char *buffer, int mode, size_t size);

There are three modes:

  1. _IOFBF (Full Buffering): The most efficient. It waits until the buffer is completely full.
  2. _IOLBF (Line Buffering): It flushes the data whenever a newline (\n) is encountered.
  3. _IONBF (No Buffering): Data goes straight to the disk immediately. Slow, but safe.

A Practical Example

If you want to ensure a log file captures every single character immediately, you can disable buffering like this:

#include <stdio.h>

int main() {
    FILE *myFile = fopen("system.log", "w");
    
    if (myFile != NULL) {
        // We pass NULL for the buffer because we aren't using one
        // _IONBF tells C to bypass the "waiting room" entirely
        setvbuf(myFile, NULL, _IONBF, 0);

        fprintf(myFile, "Critical error detected!"); 
        // This is written to the disk immediately without waiting.

        fclose(myFile);
    }
    return 0;
}

Alternatively, if you were writing a massive 1GB file, you might create a large char array of 64KB and pass it to setvbuf with _IOFBF to make the process much faster by reducing the number of hardware writes.

Key takeaway

Use setvbuf to manually adjust the "waiting room" size of your file streams, choosing between speed (large buffers) and data safety (no buffers).