C setvbuf() Function Tutorial

In this section, we will learn what the setvbuf() function is and how it works in C.

C Buffer: Function of a Buffer

When we open a file in a program to work on it, the content of the file before coming to our program is first stored in a memory location called buffer. Likewise, when we want to send data to a file, this data is first stored in a buffer. By default, the size of this memory location is decided by the underlying system.

C setvbuf() Function

Now, using the `setvbuf()` function allows us to allocate another buffer as the location from which the content of an opened file can be stored for reading or writing operations.

The prototype of the function exists in the `stdio.h` header file and so the file should be included in the program in order to use the function.

C setvbuf() Function Syntax:

Here’s the prototype of the function:

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

C setvbuf() Function Parameters

The function has 3 parameters:

  • The first parameter is the address of the allocated memory-space to the FILE-structure of the target file.
  • The second parameter is the address of the buffer that is going to be used.
  • The third parameter is used to declare how flushing on the buffer should happen.

There are three values that can be used as the argument to this parameter.

  1. _IOFBF: means fully buffered, which in this case the buffer will flush only when it’s full.
  2. _IOLBF: means line-buffered, which in this case the buffer will flush when is full or when a newline is written)
  3. _IONBF: this means non-buffered.
  • The last parameter of the function is the size of the buffer in bytes.

Note: the call to this function happens after the file has been opened and just before any other operations have been performed.

C setvbuf() Function Return Value

On a successful operation, the function will return 0. But if an error happened, a non-zero value will be returned.

Example: using setvbuf() function in C

#include <stdio.h>
#include <stdlib.h>


int main() {

    char buffer[100];

    FILE *file = fopen("G:/fileOne.txt","w");

    if (file == NULL){
        printf("Could not open the file");
        exit(EXIT_FAILURE);

    }

    setvbuf(file, buffer, _IOLBF, sizeof(buffer));

    fputs("This content is first stored in the buffer and then sent to the hard-disk\n",file);

    fclose(file);

    printf("\nDone\n");
    return 0;
}

Output:

Done
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies