setbuf() Function in C

What is setbuf() Function in C?

The setbuf() function in C is used to define the buffering behavior of a file stream. It’s part of the standard I/O library <stdio.h> and plays a key role in performance tuning by managing how input/output buffering works for file streams.

Syntax:

void setbuf(FILE *stream, char *buffer);
  • stream: A pointer to the file (e.g., stdout, stdin, or a file opened with fopen()).
  • buffer: A pointer to a buffer (a character array) that you provide. If you pass NULL, buffering is disabled.

How setbuf() Works

When you open a file using functions like fopen(), the system automatically allocates a buffer for the stream. However, you can use setbuf() to specify your own buffer or to disable buffering:

  • Custom Buffer: Provide a character array of size BUFSIZ (defined in <stdio.h>) to use as the buffer.
  • Disable Buffering: Pass NULL as the buffer to disable buffering, making the stream unbuffered.

It’s important to call setbuf() immediately after opening the file and before any other operations on the stream.

Buffering Modes in C

C provides three buffering modes:

  • Full Buffering (_IOFBF): The output is stored in the buffer and written to the file when the buffer is full. This is the default mode for files.
  • Line Buffering (_IOLBF): The output is stored until a newline character is encountered. This is typically used for standard output.
  • No Buffering (_IONBF): The output is written immediately without buffering. This is useful for real-time applications.

While setbuf() provides basic control over buffering, for more granular control, consider using setvbuf(), which allows you to specify the buffering mode and buffer size.

advertisement

Examples

Example 1: Using Custom Buffer for File Output

#include <stdio.h>
 
int main() {
    FILE *fp;
    char buffer[BUFSIZ];  // BUFSIZ is a standard buffer size macro
 
    fp = fopen("sanfoundry_output.txt", "w");
    if (fp == NULL) {
        perror("File open failed");
        return 1;
    }
 
    setbuf(fp, buffer); // Set custom buffer
 
    fprintf(fp, "Sanfoundry Quiz Result: Passed\n");
    fclose(fp);
    return 0;
}

This C program shows how to use a custom buffer when writing to a file. It opens a file named “sanfoundry_output.txt” in write mode. If the file can’t be opened, it shows an error. It then sets a custom buffer using setbuf() and writes a message to the file with fprintf(). Finally, it closes the file with fclose() to save the data.

Example 2: Disabling Buffering

Free 30-Day Python Certification Bootcamp is Live. Join Now!
#include <stdio.h>
 
int main() {
    setbuf(stdout, NULL); // Unbuffered output
 
    printf("Sanfoundry Test Started...\n");
    // Output is immediately flushed without buffering
    return 0;
}

This C program sets unbuffered output for the console using setbuf(stdout, NULL). This means anything printed with printf() is shown immediately, without waiting for the buffer to fill. It then prints “Sanfoundry Test Started…\n” and ends. Using unbuffered output is useful when you need instant feedback on the screen.

setbuf() vs setvbuf()

While setbuf() is simple, it doesn’t allow choosing the buffering mode. setvbuf() is more flexible:

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

With setvbuf(), you can specify:

  • _IOFBF for full buffering.
  • _IOLBF for line buffering.
  • _IONBF for no buffering.

Example:

setvbuf(stdout, NULL, _IONBF, 0);  // Disable buffering

When to Use setbuf()

  • You want more control over how your file streams behave.
  • You’re optimizing performance by reducing I/O overhead.
  • You need immediate output, such as in interactive programs or logging.
  • You’re working with custom hardware or embedded systems that need precise I/O timing.

When Not to Use It

  • After you’ve already performed I/O operations on the stream.
  • If you don’t fully understand the impact on performance and resource usage.
  • If you need fine-grained control over buffering—then prefer setvbuf().

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

advertisement
If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.