C library functions -setvbuf()

C Standard Library - <stdio.h>

Description

C Library Functionsint setvbuf(FILE *stream, char *buffer, int mode, size_t size)Defines how the stream should be buffered.

Declaration

Below is the declaration of the setvbuf() function.

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

Parameter

  • stream-- This is a pointer to a FILE object that identifies an open stream.
  • buffer-- This is a user-allocated buffer. If set to NULL, the function automatically allocates a buffer of the specified size.
  • mode-- This specifies the mode of file buffering:
ModeDescription
_IOFBFFull 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.
_IOLBFLine buffering: For output, data is written when a newline character is encountered or when the buffer is full, whichever comes first. For input, the buffer is filled when input is requested and the buffer is empty, up to the next newline character.
_IONBFNo buffering: No buffering is used. Each I/O operation is written immediately. The buffer and size parameters are ignored.
  • size-- This is the size of the buffer, in bytes.

Return Value

If successful, this function returns 0; otherwise, it returns a non-zero value.

Example

The following example demonstrates the usage 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 example.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 us compile and run the above program, which will produce the following result. Here, the program saves the buffered output tobuffuntil the first callfflush()until then, starts buffering output, and finally sleeps for 5 seconds. It flushes the remaining output to STDOUT before the program ends.

启用全缓冲
这里是 example.com
该输出将保存到 buff
这将在编程时出现
最后休眠五秒钟

C Standard Library - <stdio.h>

other extensions