C programming stdio.h function - int setvbuf(FILE *stream, char *buffer, int mode, size_t size)

The setvbuf() function in C programming is defined in the stdio.h header file, and it is used to set the buffer and buffer mode for the specified FILE stream. The setvbuf() function is more flexible than the setbuf() function because it allows you to specify the buffer mode and size.

The function has four parameters: the first is a pointer to the FILE stream to be buffered, the second is a pointer to the buffer, the third is an integer that specifies the buffer mode, and the fourth is a size_t value that specifies the buffer size.

The possible values for the buffer mode parameter are:

  • _IOFBF: Full buffering. The buffer is used for input and output, and data is read or written in blocks of size size.
  • _IOLBF: Line buffering. The buffer is used for input and output, and data is read or written one line at a time.
  • _IONBF: No buffering. The buffer is not used for input or output, and data is read or written directly to or from the file.

If the buffer parameter is NULL, then the setvbuf() function will automatically allocate a buffer of size size.

Here's the syntax for the setvbuf() function:

re‮‬fer to:theitroad.com
int setvbuf(FILE *stream, char *buffer, int mode, size_t size);

The function returns 0 if the buffer was set successfully, and nonzero otherwise.

Here's an example of how to use the setvbuf() function to set a buffer for a file stream:

#include <stdio.h>

int main() {
    FILE *fp;
    char buf[BUFSIZ];

    fp = fopen("example.txt", "w");

    if (setvbuf(fp, buf, _IOFBF, BUFSIZ) != 0) {
        perror("setvbuf() failed");
    }

    fprintf(fp, "This is a test message");

    fclose(fp);

    return 0;
}

In the above example, a buffer of size BUFSIZ is created, and a file named "example.txt" is opened for writing using fopen(). The setvbuf() function is called to set the buffer for the fp stream using full buffering mode. Then, a test message is written to the file using fprintf(). Finally, the file is closed using fclose().