Chapter Contents

Previous

Next
setvbuf

setvbuf



Change Stream Buffering

Portability: ISO/ANSI C conforming, UNIX compatible


SYNOPSIS
DESCRIPTION
RETURN VALUE
IMPLEMENTATION
EXAMPLE
RELATED FUNCTIONS
SEE ALSO


SYNOPSIS

#include <stdio.h>

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


DESCRIPTION

setvbuf requests a buffering mode for a stream. stream is a pointer to an open file on which no other operation has been performed. buf specifies the area that the C library uses as the buffer for stream . The mode function can have one of three values, defined as macros in <stdio.h> :
_IOFBF indicates full buffering.
_IOLBF indicates line buffering.
_IONBF indicates no buffering.

size must be greater than zero. If buf is not NULL , then the array it points to may be used instead of a buffer allocated by setvbuf . For buf , the length in bytes is indicated by size .

For FILE pointers that reference HFS files or sockets, you can use setvbuf to change the buffering mode, or the buffer size or location, or both. If setvbuf is not used, the default buffer size for HFS files and sockets is 1008 bytes. For all other file types, setvbuf has no effect. setvbuf is permitted only as the first operation following the opening of a file.


RETURN VALUE

setvbuf returns 0 if the stream can be buffered as specified by mode , or nonzero if the request cannot be honored.


IMPLEMENTATION

In this implementation, the buffering mode of a non USS stream is chosen when the file is opened and cannot be changed by setvbuf . For non USS streams, setvbuf returns 0 if the value of mode is the same as the buffering mode chosen when the file is opened. If the file is opened as a text stream, then a mode value of _IOLBF causes setvbuf to return 0. If the file is opened as a binary stream, then a mode value of _IOFBF causes setvbuf to return 0.


EXAMPLE

This example counts the number of characters in a text file. It uses the setvbuf function to request a 4K buffer for reading the file. On some systems, this may improve speed of access; on OS/390 or CMS, this has no effect.

#include <stdio.h>
#include <stdlib.h>

#define BUFFER_SIZE 4000

char *_style = "tso"; /* Use TSO-style filenames by default. */
main()
{
  FILE *in;
  int ch;
  char fname[80];
  int count = 0;

  puts("Enter the file you want to read:");
  gets(fname);
  in = fopen(fname, "r");
  if (!in){
     puts("That file cannot be opened.");
     exit(EXIT_FAILURE);
  }
  setvbuf(in, NULL, _IOFBF, BUFFER_SIZE);
     /* Ask for a large buffer.                              */
  while((ch = getc(in)) != EOF) ++count;
  printf("That file contains %d characters.\n", count);
  exit(EXIT_SUCCESS);
}


RELATED FUNCTIONS

setbuf


SEE ALSO


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.