C library function -fflush()
C Standard Library - <stdio.h>
Description
C Library Functionsint fflush(FILE *stream)Used to flush the output buffer.
fflush() is a function in the C standard library that immediately writes the data in the buffer to the file or device associated with the stream.
For input streams, its behavior is undefined, and calling this function on input streams should be avoided.
Declaration
Below is the declaration of the fflush() function.
int fflush(FILE *stream)
Parameter
stream-- A pointer to type FILE, indicating the target stream whose buffer needs to be flushed. FILE is a structure representing an open file stream.
- if
streamisNULL, then it will flush the buffers of all output streams. - if
streamIf it is a file pointer, then flush the output buffer of that file stream.
- if
Return Value
If the buffer is successfully flushed,
fflush()Returns 0.If an error occurs, returns
EOF, and sets the error indicator (ferror)。
Example
The following example demonstrates the usage of the fflush() function.
Example
Code explanation:
Open a File: Use
fopen()Open a file namedexample.txtThe file is opened for writing.Write data: Use
fprintf()The string"Hello, World!"Write to the file.Flush the buffer: Call
fflush(fp)Ensure that data is written to the file immediately, rather than remaining in the buffer.Check the return value: if
fflush()Returns 0, indicating that the buffer was flushed successfully; otherwise, it indicates that an error occurred.Close a File: Use
fclose()Close the file.
Data successfully written to the file.
The program opens the file example.txt and writes the string "Hello, World!".
fflush(fp) successfully flushes the buffer and returns 0, so it prints "Data successfully written to the file."
The content of the file example.txt will be:
Hello, World!other extensions