cfclosefflush

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 ?


Solution

  • 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.