RAD Studio
ContentsIndex
PreviousUpNext
setvbuf

Header File 

stdio.h  

Category 

Input/output Routines 

Prototype 

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

Description 

Assigns buffering to a stream. 

setvbuf causes the buffer buf to be used for I/O buffering instead of an automatically allocated buffer. It is used after the given stream is opened. 

If buf is null, a buffer will be allocated using malloc; the buffer will use size as the amount allocated. The buffer will be automatically freed on close. The size parameter specifies the buffer size and must be greater than zero. 

The parameter size is limited by the constant UINT_MAX as defined in limits.h. 

stdin and stdout are unbuffered if they are not redirected; otherwise, they are fully buffered. Unbuffered means that characters written to a stream are immediately output to the file or device, while buffered means that the characters are accumulated and written as a block.

  • The type parameter is one of the following:
 

 

_IOFBF 
fully buffered file. When a buffer is empty, the next input operation will attempt to fill the entire buffer. On output, the buffer will be completely filled before any data is written to the file. 
_IOLBF 
line buffered file. When a buffer is empty, the next input operation will still attempt to fill the entire buffer. On output, however, the buffer will be flushed whenever a newline character is written to the file. 
_IONBF 
unbuffered file. The buf and size parameters are ignored. Each input operation will read directly from the file, and each output operation will immediately write the data to the file. 

A common cause for error is to allocate the buffer as an automatic (local) variable and then fail to close the file before returning from the function where the buffer was declared. 

Return Value 

On success, setvbuf returns 0. 

On error (if an invalid value is given for type or size, or if there is not enough space to allocate a buffer), it returns nonzero. 

Example  

#include <stdio.h>
int main(void)
{
   FILE *input, *output;
   char bufr[512];
   input = fopen("file.in", "r+b");
   output = fopen("file.out", "w");
   /* set up input stream for minimal disk access,
      using our own character buffer */
if (setvbuf(input, bufr, _IOFBF, 512) != 0)
      printf("failed to set up buffer for input file\n");
   else
      printf("buffer set up for input file\n");
   /* set up output stream for line buffering using space that
      will be obtained through an indirect call to malloc */
   if (setvbuf(output, NULL, _IOLBF, 132) != 0)
      printf("failed to set up buffer for output file\n");
   else
      printf("buffer set up for output file\n");
   /* perform file I/O here */
   /* close files */
   fclose(input);
   fclose(output);
   return 0;
}

Portability

POSIX 
Win32 
ANSI C 
ANSI C++ 
Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
What do you think about this topic? Send feedback!