A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/c_standard_library/c_function_setbuf.htm below:

C Library - setbuf() function

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 −

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.

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4