w3resource

C setvbuf() function

C library function - setvbuf()

The setvbuf() function is used to control over the buffering strategy and buffer size for a specified stream. The stream must refer to a file that has been opened, but not read or written to.

Syntax:

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

setvbuf() Parameters:

Name Description Required /Optional
stream Identifies an address for a file descriptor, which is an area of memory associated with an input or output stream. Required
buffer The system uses the buffer, which you specify, for input/output buffering instead of the default system-allocated buffer for the given stream. Required
mode A mode for file buffering Required
size Size of the buffer in bytes. Required

The Mode must be one of the following:

Mode Description
_IOFBF Full buffering is used for input and output. Use buf as the buffer and size as the size of the buffer.
_IOLBF Line buffering is used. The buffer is deleted when a new-line character is written, when the buffer is full, or when input is requested.
_IONBF No buffer is used.

Return value from setvbuf()

  • Upon successful completion, setvbuf() shall return 0.
  • Otherwise, it shall return a non-zero value if an invalid value is given for type or if the request cannot be honored, and may set errno to indicate the error.

Example: setvbuf() function

This example opens the file test.txt for writing. To create a buffer of size BUFSIZ, it calls the setbuf() function. Strings are written to the stream using the buffer buf, which contains the string before it is flushed to the file.

#include <stdio.h>
#define  BUF_SIZE  1024
 
char buf[BUF_SIZE];
FILE *stream1, *stream2;
 
int main(void)
{
   stream1 = fopen("file1.txt", "r");
   stream2 = fopen("file2.txt", "r");
 
   /* stream1 uses a user-assigned buffer of BUF_SIZE bytes */
   if (setvbuf(stream1, buf, _IOFBF, sizeof(buf)) != 0)
      printf("Wrong type or size of buffer\n");
 
   /* stream2 is unbuffered                                  */
   if (setvbuf(stream2, NULL, _IONBF, 0) != 0)
      printf("Wrong type or size of buffer\n"); 
 /*  This is a program fragment and not a complete function example  */
}

C Programming Code Editor:

Previous C Programming: C setbuf()
Next C Programming: C tmpfile()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming/stdio/c_library_method_setvbuf.php