C library function - fflush()
Description
C library function *int fflush(FILE stream) Used to flush the output buffer.
fflush() is a function in the C standard library that immediately writes data in the buffer to the file or device associated with the stream.
For input streams, its behavior is undefined, and you should avoid calling this function on input streams.
Declaration
The following is the declaration of the fflush() function.
int fflush(FILE *stream)
Parameters
-
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 both the
streamisNULL, the buffers of all output streams are flushed. - If both the
streamis a file pointer, the output buffer of that file stream is flushed.
Return Value
-
If the buffer is flushed successfully,
fflush()returns 0. -
If an error occurs, return
EOF, and set the error indicator (ferror).
Example
The following example demonstrates the use of the fflush() function.
Example
#include
<
stdio.h
int
main
(
)
{
FILE
fp;
char
filename
=
"
example.txt
"
;
char
data
=
"
Hello, World!
"
;
// Open file for writing
fp
=
fopen
(
filename
,
"
w
"
)
;
if
(
fp
==
NULL
)
{
printf
(
"
Unable to open file %s
\
n
"
,
filename
)
;
return
1
;
}
// Write data to the file
fprintf
(
fp
,
"
%s
"
,
data
)
;
// Flush the buffer to ensure the data is written to the file
if
(
fflush
(
fp
)
==
0
)
{
printf
(
"
Data successfully written to the file.
\
n
"
)
;
}
else
{
printf
(
"
An error occurred while flushing the buffer.
\
n
"
)
;
}
// Close file
fclose
(
fp
)
;
return
0
;
}
Code explanation:
-
Opening a File: Using
fopen()Open a file namedexample.txtfor writing. -
Write the data: Using
fprintf()Add the first"Hello, World!"Write to the file. -
Flush the buffer: call
fflush(fp)to ensure the data is written to the file immediately rather than remaining in the buffer. -
Check the return value: If
fflush()Returns 0, indicating the buffer was flushed successfully; otherwise, an error occurred. -
Closing a File: Using
fclose()Close 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 "Data successfully written to the file." is printed.
The content of the file example.txt will be:
Hello, World!
C Standard Library -