C Function Setvbuf
# C Library Function - setvbuf()
The `setvbuf()` function is a standard C library function defined in the `` header. It allows developers to control and customize the buffering behavior of an open file stream.
By default, standard I/O streams are buffered to optimize performance. With `setvbuf()`, you can change the buffering mode (fully buffered, line buffered, or unbuffered), specify a custom user-allocated buffer, and define the buffer size.
---
## Syntax
```c
int setvbuf(FILE *stream, char *buffer, int mode, size_t size);
```
### Parameters
* **`stream`**: A pointer to a `FILE` object that identifies an open stream.
* **`buffer`**: A pointer to a user-allocated character array to be used as the buffer.
* If set to `NULL`, the function automatically allocates a buffer of the specified `size`.
* **`mode`**: Specifies the buffering mode for the stream. It must be one of the following macro constants:
| Mode | Description |
| :--- | :--- |
| `_IOFBF` | **Fully Buffered**: For output, data is written to the destination once the buffer is completely full. For input, the buffer is filled when an input operation is requested and the buffer is empty. |
| `_IOLBF` | **Line Buffered**: For output, data is written to the destination when a newline character (`\n`) is encountered or when the buffer is full. For input, the buffer is filled up to the next newline character when input is requested. |
| `_IONBF` | **Unbuffered**: No buffering is used. Each I/O operation is written directly to the destination immediately. The `buffer` and `size` parameters are ignored. |
* **`size`**: The size of the buffer in bytes (of type `size_t`).
### Return Value
* Returns **`0`** on success.
* Returns a **non-zero** value if an invalid mode is requested or if the request cannot be honored (for example, if the function is called after operations have already begun on the stream).
---
## Code Example
The following example demonstrates how to use `setvbuf()` to set up a fully buffered stream (`_IOFBF`) on `stdout`. It shows how output is held in the buffer until `fflush()` is explicitly called or the program terminates.
```c
#include
#include
#include
int main()
{
char buff;
// Initialize the buffer with null characters
memset(buff, '\0', sizeof(buff));
// This message is printed immediately because stdout is line-buffered by default in terminal environments
fprintf(stdout, "Enabling full buffering\n");
// Set stdout to fully buffered mode using our custom buffer 'buff'
setvbuf(stdout, buff, _IOFBF, 1024);
// The following outputs are written to 'buff' and will not appear on the screen yet
fprintf(stdout, "This is YouTip.com\n");
fprintf(stdout, "This output is currently saved in the buffer 'buff'\n");
// Force the buffer to flush and write the accumulated data to stdout
fflush(stdout);
// The following outputs are buffered again
fprintf(stdout, "This text is buffered and will appear later\n");
fprintf(stdout, "Sleeping for 5 seconds...\n");
// Sleep for 5 seconds. You will see that the previous two lines do not print until the sleep ends
sleep(5);
return(0);
}
```
### Output Behavior
When you compile and run the program, you will observe the following:
1. `"Enabling full buffering"` prints immediately.
2. `"This is YouTip.com"` and `"This output is currently saved in the buffer 'buff'"` print immediately after because `fflush(stdout)` is called.
3. The program pauses for 5 seconds. During this pause, the last two lines are **not** visible on the screen because they are held in the buffer.
4. Once the program finishes execution, the remaining buffered text is automatically flushed and printed to the terminal:
```text
Enabling full buffering
This is YouTip.com
This output is currently saved in the buffer 'buff'
This text is buffered and will appear later
Sleeping for 5 seconds...
```
---
## Important Considerations
1. **Timing of the Call**: You must call `setvbuf()` **after** opening the stream but **before** performing any input or output operations on it. Calling `setvbuf()` after read/write operations have started results in undefined behavior.
2. **Buffer Lifetime**: If you provide a custom buffer (a non-null pointer for the `buffer` parameter), you must ensure that the buffer's lifetime extends until the stream is closed. For example, do not use a local automatic variable inside a function as a buffer if the stream remains open after the function returns.
3. **Default Buffering**:
* Standard error (`stderr`) is unbuffered (`_IONBF`) by default.
* Standard output (`stdout`) is line-buffered (`_IOLBF`) when connected to an interactive terminal, and fully buffered (`_IOFBF`) when redirected to a file or pipe.
YouTip