Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Function - setvbuf()

C Library Function - setvbuf()

C Standard Library - <stdio.h> C Standard Library -

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

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.

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 - <stdio.h> C Standard Library -