C Programming/stdio.h/setvbuf

is a function in standard C which lets the programmer control the buffering of a file stream. It is declared in ; its function prototype is:

The stream argument is a pointer to the file stream for which the relevant buffering operations will be performed; buf is a character array of size in length, or a null pointer; and mode is the kind of buffering desired:, for fully buffered,   for line buffered and   for unbuffered. These three macros are defined in . returns zero on success or nonzero on failure.

If buf is a null pointer, the system will dynamically allocate a buffer of the specified size (size characters). If mode is, the stream I/O will not be buffered, causing each subsequent I/O operation on the stream to be performed immediately, and the buf and size arguments are ignored.

A related function,  also controls the buffering of a file stream. Unlike,   takes only two arguments. The prototype is:

's behavior is equivalent to:

That is, if buf is not, set the stream to fully buffered using the given buffer; otherwise, set the stream to unbuffered. If a buffer is provided to, it must be at least   bytes long. The function always succeeds.

The code below is very unstable and might not work properly on specific compilers. It may even buffer overflow.. C99 says that setvbuf may not be called after writing to the stream, so this code invokes undefined behavior. C99 footnote 230 (non-normative) says the stream should be closed before buf is deallocated at the end of main.

Example
The output of this program should be Hello world followed by a newline. Note this example is broken as it implements what the manpage clearly labels as a bug: The buffer needs to be still there when the stream is closed. Here, the buffer goes away upon leaving main, but the stream is closed only afterwards when the program terminates.