Previous Page
Next Page

setvbuf

Sets up I/O buffering for an open file

#include <stdio.h>
int setvbuf ( FILE * restrict fp , char * restrict buffer , int mode ,
             size_t size  );

The setvbuf( ) function specifies the buffering conditions for input and/or output using the stream associated with the FILE pointer fp. You may call the setvbuf( ) function only after the file has been successfully opened, and before any file I/O operations have taken place.

The mode parameter determines the type of buffering requested. Symbolic constants for the permissible values are defined in stdio.h as follows:


_IOFBF

Fully buffered: On read and write operations, the buffer is filled completely before data appears from the source or at the destination.


_IOLBF

Line buffered: On read and write operations, the buffer is filled until a newline character occurs before data appears from the source or at the destination. Furthermore, if a requested read operation exceeds the contents of the buffer, then the buffer contents are written to the file before more data is read from the file into the buffer.


_IONBF

Not buffered: Data is read from or written to the file directly. The buffer and size parameters are ignored.

You can provide a buffer for the file by passing its address and size in the arguments buffer and size. The setvbuf( ) function is not required to use the buffer you provide, however. If buffer is a null pointer, setvbuf( ) dynamically allocates a buffer of the specified size. Otherwise, you must make sure that the buffer remains available until you close the file. The function returns 0 on success; any other value indicates failure or an invalid mode argument.

Example

#define MAX_LINE 4096
FILE *fp_linewise = fopen( "output.txt", "a+" );
unsigned char *iobuffer = malloc( MAX_LINE );
if ( iobuffer != NULL )
{ // Buffer output up to each '\n'.
  if (setvbuf( fp_linewise, iobuffer, _IOLBF, MAX_LINE ))
    fprintf( stderr, "setvbuf( ) failed; unable to set line-buffering.\n" ),
    exit( -2 );
}
else
  fprintf( stderr, "malloc( ) failed; no point in calling setvbuf( ).\n" ),
  exit( -1 );

See Also

setbuf( ), fopen( ), malloc( )


Previous Page
Next Page