fflush() — Write Buffer to File
Format
#include <stdio.h>
int fflush(FILE *stream);
Language Level
ANSI
Threadsafe
Yes
Description
The fflush()
function
causes the system to empty the buffer that is associated with the
specified output stream, if possible. If
the stream is open for input, the fflush()
function
undoes the effect of any ungetc()
function.
The stream remains open after the call.
If stream is NULL,
the system flushes all open streams.
Note: The system automatically
deletes buffers when you close the stream, or when a program ends
normally without closing the stream.
Return Value
The fflush()
function
returns the value 0 if it successfully deletes the buffer.
It returns EOF if an error occurs.
The value of errno can be set to:
- Value
- Meaning
- ENOTOPEN
- The file is not open.
- ERECIO
- The file is opened for record I/O.
- ESTDIN
stdin
cannot be opened.- EIOERROR
- A non-recoverable I/O error occurred.
- EIORECERR
- A recoverable I/O error occurred.
The fflush()
function
is not supported for files that are opened with type=record.
Example
This example deletes a stream buffer.
#include <stdio.h>
int main(void)
{
FILE *stream;
int ch;
unsigned int result = 0;
stream = fopen("mylib/myfile", "r");
while ((ch = getc(stream)) != EOF && isdigit(ch))
result = result * 10 + ch - '0';
if (ch != EOF)
ungetc(ch,stream);
fflush(stream); /* fflush undoes the effect of ungetc function */
printf("The result is: %d\n", result);
if ((ch = getc(stream)) != EOF)
printf("The character is: %c\n", ch);
}