COHERENT manpages

This page displays the COHERENT manpage for setvbuf() [Set alternative file-stream buffer].

List of available manpages
Index


setvbuf() -- STDIO Function (libc)

Set alternative file-stream buffer
#include <stdio.h>
int setvbuf(fp, buffer, mode, size)
FILE *fp; char *buffer; int mode; size_t size;

When the functions fopen()  and freopen() open a stream, they automatically
establish a buffer  for it.  The buffer is BUFSIZ  bytes long.  BUFSIZ is a
manifest constant that is defined in the header stdio.h.

The function setvbuf() alters the buffer used with the stream pointed to by
fp from its default buffer to buffer. Unlike the related function setbuf(),
it also  allows you set the size  of the new buffer as well  as the form of
buffering.

buffer is the address of the new buffer.  size is its size, in bytes.  mode
is the manner in which you wish the stream to be buffered, as follows:

    _IOFBF   Fully buffered
    _IOLBF   Line-buffered
    _IONBF   No buffering

These constants are defined in the header stdio.h.

You should  call setvbuf() after  a stream has  been opened but  before any
data  have been  written to  or  read from  the stream.   For example,  the
following give fp a 50-byte buffer that is line-buffered:

    char buffer[50];
    FILE *fp;

    fopen(fp, "r");
    setvbuf(fp, buffer, _IOLBF, sizeof(buffer));

On  the other  hand, the  following  turns off  buffering for  the standard
output stream:

    setvbuf(stdout, NULL, _IONBF, 0);

setvbuf() returns  zero if the  new buffer could  be established correctly.
It returns a value other than zero if something went wrong or if an invalid
parameter is given for mode or size.

Example

This example uses setvbuf() to turn off buffering and echo.

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

main(void)
{
    int c;

    if(setvbuf(stdin,  NULL, _IONBF, 0))
        fprintf(stderr, "Couldn't turn off stdin buffer\n");

    if(setvbuf(stdout,  NULL, _IONBF, 0))
        fprintf(stderr, "Couldn't turn off stdout buffer\n");

    while((c = getchar()) != EOF)
        putchar(c);
}

See Also

fclose(),
fflush(),
fopen(),
freopen(),
libc,
setbuf()
ANSI Standard, §7.9.5.6

Notes

setvbuf() affects  the buffering of an  I/O stream but does  not affect any
buffering that performed by the device  upon which the text is typed.  Some
devices  (e.g.,  /dev/tty)  are  buffered  by  default.  To  turn  off  the
buffering of  what a user  types, you must  both turn off  buffering on the
input stream and turn off buffering  on the device itself.  For example, to
turn off  buffering on a terminal  device, you must both  call setvbuf() to
change the size of the input  buffering to zero, and call stty() to put the
terminal device into raw mode.