Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C library function - fflush()

C library function - fflush()

C Standard Library - <stdio.h> C Standard Library -

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

- If `stream` is `NULL`, the buffers of all output streams are flushed. - If `stream` is a file pointer, the output buffer of that file stream is flushed.

Return Value

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:



数据成功写入文件。

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 - <stdio.h> C Standard Library -