
- C Library - Home
- C Library - <assert.h>
- C Library - <complex.h>
- C Library - <ctype.h>
- C Library - <errno.h>
- C Library - <fenv.h>
- C Library - <float.h>
- C Library - <inttypes.h>
- C Library - <iso646.h>
- C Library - <limits.h>
- C Library - <locale.h>
- C Library - <math.h>
- C Library - <setjmp.h>
- C Library - <signal.h>
- C Library - <stdalign.h>
- C Library - <stdarg.h>
- C Library - <stdbool.h>
- C Library - <stddef.h>
- C Library - <stdio.h>
- C Library - <stdlib.h>
- C Library - <string.h>
- C Library - <tgmath.h>
- C Library - <time.h>
- C Library - <wctype.h>
- C Programming Resources
- C Programming - Tutorial
- C - Useful Resources
C Library - setbuf() function
The C Library setbuf() function is used to define a buffer for a file stream. This function allows programmers to either enable or disable buffering for a file stream by setting a custom buffer or setting it to NULL. Buffering is a technique used to improve the efficiency of input/output operations.
Syntax
Following is the C library syntax of the setbuf() function −
void setbuf(FILE *stream, char *buffer);
Parameters
This function accepts two parameter −
- FILE *stream: This is a pointer to a FILE object that identifies the stream for which buffering is to be set.
- char *buffer: This is a pointer to a character array to be used as the buffer for the stream. If buffer is NULL, buffering is disabled for the given stream.
Return Value
The setbuf function does not return a value.
Example 1: Setting a Custom Buffer
This example sets a custom buffer for the file stream fp before writing to it. The custom buffer buf is of size BUFSIZ, which is a macro defining the default buffer size.
Below is the illustration of the C library setbuf() function.
#include <stdio.h> int main() { FILE *fp; char buf[BUFSIZ]; fp = fopen("example1.txt", "w"); if (fp == NULL) { perror("Error opening file"); return 1; } setbuf(fp, buf); fprintf(fp, "This is a test string.\n"); fclose(fp); return 0; }
Output
The above code produces following result in example1.txt file−
This is a test string.
Example 2: Using a Small Buffer
This example uses a very small buffer (10 bytes) for the file stream fp. This might not be efficient but demonstrates how to set a custom buffer size.
#include <stdio.h> int main() { FILE *fp; char small_buf[10]; fp = fopen("example3.txt", "w"); if (fp == NULL) { perror("Error opening file"); return 1; } setbuf(fp, small_buf); fprintf(fp, "This text will be buffered using a small buffer.\n"); fclose(fp); return 0; }
Output
After execution of above code, we get the following result in the example3.txt file
This text will be buffered using a small buffer.