C Function Fflush
# C Library Function - fflush()
The `fflush()` function is a standard library function in C (defined in the `` header) used to flush the output buffer of a stream. It forces any buffered but unwritten data to be written immediately to the associated file, device, or terminal.
---
## Description
In C, I/O operations are typically buffered to improve performance. Instead of writing data directly to the disk or device byte-by-byte, the system stores it in a temporary memory area called a buffer. The buffer is automatically flushed when it becomes full, when the file is closed, or when the program terminates normally.
However, there are scenarios where you need to ensure that data is written immediately (for example, before a critical operation or during real-time logging). The `fflush()` function allows you to manually trigger this process.
> **Important Note on Input Streams:** According to the C standard, the behavior of `fflush()` on an input stream (such as `stdin`) is **undefined**. While some compilers (like MSVC on Windows) may clear the input buffer, this behavior is non-portable. You should avoid calling `fflush()` on input streams in standard-compliant code.
---
## Syntax
The prototype for the `fflush()` function is as follows:
```c
int fflush(FILE *stream);
```
### Parameters
* **`stream`**: A pointer to a `FILE` object that identifies the stream whose buffer needs to be flushed.
* If `stream` points to an open output file or terminal stream, any unwritten data in its buffer is written to the destination.
* If `stream` is `NULL`, **all** open output streams are flushed.
### Return Value
* **`0`**: On success, the function returns `0`.
* **`EOF`**: If an error occurs, the function returns `EOF` (End of File) and sets the error indicator for the stream (which can be checked using `ferror()`).
---
## Code Example
The following example demonstrates how to use `fflush()` to ensure data is written to a file immediately.
```c
#include
int main() {
FILE *fp;
char *filename = "example.txt";
char *data = "Hello, World!";
// Open the file for writing
fp = fopen(filename, "w");
if (fp == NULL) {
printf("Failed to open file %s\n", filename);
return 1;
}
// Write data to the stream's buffer
fprintf(fp, "%s", data);
// Flush the buffer to guarantee the data is written to the file immediately
if (fflush(fp) == 0) {
printf("Data successfully flushed and written to file.\n");
} else {
printf("An error occurred while flushing the buffer.\n");
}
// Close the file
fclose(fp);
return 0;
}
```
### Code Explanation:
1. **Opening the File**: The program opens a file named `example.txt` in write mode (`"w"`) using `fopen()`.
2. **Writing Data**: The `fprintf()` function writes the string `"Hello, World!"` to the stream. At this point, the data may still reside in the application's memory buffer and might not yet be written to the physical disk.
3. **Flushing the Buffer**: Calling `fflush(fp)` forces the system to write the buffered data to `example.txt` immediately.
4. **Checking the Return Value**: If `fflush()` returns `0`, it confirms the flush was successful.
5. **Closing the File**: The file is safely closed using `fclose()`.
### Output
When you run the program, it will output:
```text
Data successfully flushed and written to file.
```
The contents of the newly created `example.txt` file will be:
```text
Hello, World!
```
---
## Key Considerations
### 1. Undefined Behavior with `stdin`
A common mistake among beginners is using `fflush(stdin)` to clear the input buffer (for example, to discard leftover newline characters before reading user input).
* **Why you should avoid it**: The C standard states that `fflush()` is only defined for output streams. Using it on `stdin` makes your code non-portable and prone to unexpected behavior on systems like Linux (GCC).
* **Alternative**: To clear the input buffer safely in standard C, use a loop to consume remaining characters:
```c
int c;
while ((c = getchar()) != '\n' && c != EOF);
```
### 2. Automatic Flushing
You do not always need to call `fflush()` manually. The system automatically flushes buffers under the following conditions:
* When the stream is closed using `fclose()`.
* When the program terminates normally (via `return` from `main` or calling `exit()`).
* For line-buffered streams (like `stdout` when connected to a terminal), whenever a newline character (`\n`) is written.
* When an input operation is requested on a stream that shares the same buffer.
### 3. Performance Impact
While `fflush()` is useful for ensuring data integrity (e.g., preventing data loss during a crash), calling it too frequently can significantly degrade performance. Frequent flushing bypasses the efficiency benefits of I/O buffering by forcing constant, slow disk/hardware writes. Use it selectively.
YouTip