Format
#include <stdio.h> int setvbuf(FILE *stream, char *buf, int type, size_t size);
Language Level: ANSI, XPG4
setvbuf allows control over the buffering strategy and buffer
size for a specified stream.
The stream must refer to a file that has been opened, but not read or written to. The array pointed to by buf designates an area that you provide that the C library may choose to use as a buffer for the stream. A buf value of NULL indicates that no such area is supplied and that the C library is to assume responsibility for managing its own buffers for the stream. If you supply a buffer, it must exist until the stream is closed.
The type must be one of the following:
| Value | Meaning |
| _IONBF | No buffer is used. |
| _IOFBF | Full buffering is used for input and output. Use buf as the buffer and size as the size of the buffer. |
| _IOLBF | Line buffering is used. The buffer is flushed when a new-line character is written, when the buffer is full, or when input is requested. |
If type is _IOFBF or _IOLBF, size is the size of the supplied buffer. If buf is NULL, the C library takes size as the suggested size for its own buffer. If type is _IONBF, both buf and size are ignored.
The value for size must be greater than 0.
Return Value
setvbuf returns 0 if successful. It returns nonzero if
an invalid value was specified in the parameter list, or if the
request cannot be performed.
Note: The array used as the buffer must still exist when the specified stream is closed. For example, if the buffer is declared within the scope of a function block, the stream must be closed before the function is terminated and frees the storage allocated to the buffer.
Example
This example sets up a buffer of buf for stream1 and
specifies that input to stream2 is to be unbuffered.
#include <stdio.h> #include <stdlib.h>
#if (1== __TOS_02__) #define FILENAM1 "myfile1.dat" /* OS/2 file name */ #define FILENAM2 "myfile2.dat" /* OS/2 file name */ #else #define FILENAM1 "myfile1.dat" /* Windows file name */ #define FILENAM2 "myfile2.dat" /* Windows file name */ #endif
#define BUF_SIZE 1024
char buf[BUF_SIZE]; FILE *stream1, *stream2;
int main(void)
{
int flag = EXIT_SUCCESS;
stream1 = fopen(FILENAM1, "r");
stream2 = fopen(FILENAM2, "r");
/* stream1 uses a user-assigned buffer of BUF_SIZE bytes */
if (setvbuf(stream1, buf, _IOFBF, sizeof(buf)) != 0)
printf("Incorrect type or size of buffer\n");
/* stream2 is unbuffered */
if (setvbuf(stream2, NULL, _IONBF, 0) != 0){
printf("Incorrect type or size of buffer\n");
flag = EXIT_FAILURE;
}
fclose(stream1);
fclose(stream2);
return flag;
}
![]()
fclose -- Close Stream
fflush -- Write Buffer to File
_flushall -- Write Buffers to Files
fopen -- Open Files
setbuf -- Control Buffering
<stdio.h>