Chetan Phadtale
Chetan Phadtale

Reputation: 13

Is it safe to call fflush() without fclose()

I am writing logger for my embedded application. I need to write all logs to file. Currently I am opening and closing file for every write.

To improve performance, is it safe to keep log file open throughout the application scope and call fflush() without closing file for every write ?

Upvotes: 1

Views: 1381

Answers (2)

chqrlie
chqrlie

Reputation: 144949

It should be safe to just call fflush() after every log write and to keep the file open, but it is highly advisable to open the file in append mode, especially if other processes write to the same log file. In this case, it would still not suffice to ensure atomic writes.

Upvotes: 0

陈敏华
陈敏华

Reputation: 1505

If you read the linux programmer's manual, you will find out that fclose will "flushes the stream pointed to by stream and closes the underlying file descriptor". So, you can just call fclose() without fflush().

If you want to write in same file multiple times. you can hold the file opened, and just call fflush multiple times. "fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function".

In a word, fflush write buffered data to file, fclose write buffered data and close file.

Upvotes: 2

Related Questions