C Library Function - setvbuf()
Description
C Library Function **int setvbuf(FILE stream, char buffer, int mode, size_t size) Defines how the stream stream should be buffered.
Declaration
The following is the declaration of the setvbuf() function.
int setvbuf(FILE *stream, char *buffer, int mode, size_t size)
Parameters
- stream -- This is a pointer to a FILE object that identifies an open stream.
- buffer -- This is the buffer allocated to the user. If set to NULL, the function automatically allocates a buffer of the specified size.
- mode -- This specifies the file buffering mode:
| Mode | Description |
|---|---|
| _IOFBF | Full buffering: For output, data is written all at once when the buffer is full. For input, the buffer is filled when input is requested and the buffer is empty. |
| _IOLBF | Line buffering: For output, data is written when a newline character is encountered or when the buffer is full, depending on the situation. For input, the buffer is filled when input is requested and the buffer is empty, until the next newline character is encountered. |
| _IONBF | No buffering: No buffering is used. Every I/O operation is written immediately. The buffer and size arguments are ignored. |
- size -- This is the size of the buffer, in bytes.
Return Value
On success, the function returns 0; otherwise it returns a nonzero value.
Example
The following example demonstrates the use of the setvbuf() function.
Example
#include
<
stdio.h
#include
<
unistd.h
#include
<
string.h
int
main
(
)
{
char
buff
[
1024
];
memset
(
buff
, '\
0
',
sizeof
(
buff
)
)
;
fprintf
(
stdout
,
"
Enable full buffering
\
n
"
)
;
setvbuf
(
stdout
,
buff
,
_IOFBF
,
1024
)
;
fprintf
(
stdout
,
"
This is runoob.com
\
n
"
)
;
fprintf
(
stdout
,
"
This output will be saved to buff
\
n
"
)
;
fflush
(
stdout
)
;
fprintf
(
stdout
,
"
This will appear when programming
\
n
"
)
;
fprintf
(
stdout
,
"
Finally, sleep for five seconds
\
n
"
)
;
sleep
(
5
)
;
return
(
0
)
;
}
Let's compile and run the above program, which will produce the following result. Here, the program saves the buffered output to buff, until the first call to fflush() , after which it starts buffering output and finally sleeps for 5 seconds. Before the program ends, it sends the remaining output to STDOUT.
启用全缓冲
这里是 runoob.com
该输出将保存到 buff
这将在编程时出现
最后休眠五秒钟
C Standard Library -