setvbuf Function

Defines the stream to be buffered and the buffer size.

Include

<stdio.h>

Prototype

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

Arguments

stream pointer to the open stream
buf user allocated buffer
mode type of buffering
size size of buffer

Return Value

Returns 0 if successful

Remarks

setvbuf must be called after fopen but before any other function calls that operate on the stream. For mode, use one of the following:

_IOFBF – for full buffering

_IOLBF – for line buffering

_IONBF – for no buffering

This function requires a heap.

Example

#include <stdio.h> /* for setvbuf, fopen, */
                   /* printf, FILE, NULL, */
                   /* _IONBF, _IOFBF      */

int main(void)
{
  FILE *myfile1, *myfile2;
  char buf[256];
  if ((myfile1 = fopen("afile1", "w+")) != NULL)
  {
    if (setvbuf(myfile1, NULL, _IONBF, 0) == 0)
      printf("myfile1 has no buffering\n");
    else
      printf("Unable to define buffer stream "
             "and/or size\n");
  }
  fclose(myfile1);
  if ((myfile2 = fopen("afile2", "w+")) != NULL)
  {
    if (setvbuf(myfile2, buf, _IOFBF, sizeof(buf)) ==
       0)
      printf("myfile2 has a buffer of %d "
             "characters\n", sizeof(buf));
    else
      printf("Unable to define buffer stream "
             "and/or size\n");
  }
  fclose(myfile2);
}

Example Output

myfile1 has no buffering
myfile2 has a buffer of 256 characters