#### 12.20.2 Flushing Buffers

Flushing output on a buffered stream means transmitting all accumulated characters to the file. There are many circumstances when buffered output on a stream is flushed automatically:

- When you try to do output and the output buffer is full.
- When the stream is closed. See Closing Streams.
- When the program terminates by calling `exit`. See Normal Termination.
- When a newline is written, if the stream is line buffered.
- Whenever an input operation on any stream actually reads data from its file.

If you want to flush the buffered output at another time, call `fflush`, which is declared in the header file `stdio.h`.

— Function: int fflush (FILE *stream)

> This function causes any buffered output on stream to be delivered to the file. If stream is a null pointer, then `fflush` causes buffered output on all open output streams to be flushed.

> This function returns `EOF` if a write error occurs, or zero otherwise.

— Function: int fflush_unlocked (FILE *stream)

> The `fflush_unlocked` function is equivalent to the `fflush` function except that it does not implicitly lock the stream.

The `fflush` function can be used to flush all streams currently opened. While this is useful in some situations it does often more than necessary since it might be done in situations when terminal input is required and the program wants to be sure that all output is visible on the terminal. But this means that only line buffered streams have to be flushed. Solaris introduced a function especially for this. It was always available in the GNU C Library in some form but never officially exported.

— Function: void _flushlbf (void)

> The `_flushlbf` function flushes all line buffered streams currently opened.

> This function is declared in the `stdio_ext.h` header.

Compatibility Note: Some brain-damaged operating systems have been known to be so thoroughly fixated on line-oriented input and output that flushing a line buffered stream causes a newline to be written! Fortunately, this “feature” seems to be becoming less common. You do not need to worry about this with the GNU C Library.

In some situations it might be useful to not flush the output pending for a stream but instead simply forget it. If transmission is costly and the output is not needed anymore this is valid reasoning. In this situation a non-standard function introduced in Solaris and available in the GNU C Library can be used.

— Function: void __fpurge (FILE *stream)

> The `__fpurge` function causes the buffer of the stream stream to be emptied. If the stream is currently in read mode all input in the buffer is lost. If the stream is in output mode the buffered output is not written to the device (or whatever other underlying storage) and the buffer the cleared.

> This function is declared in `stdio_ext.h`.