1

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 ?

  • 1
    Flushing is probably better than not flushing, but beyond that it is very implementation-defined, so you should provide information about the operating system, board, specs etc. – Antti Haapala -- Слава Україні Mar 04 '20 at 08:28
  • 1
    Yes, `fflush` is not dependent on a `fclose` (the file stream should be open) – David C. Rankin Mar 04 '20 at 08:28
  • `fflush` writes the remaining bytes in the write buffer to the underlying file write function ([`write`](http://man7.org/linux/man-pages/man2/write.2.html) under Linux, or any other implementation specific stuff), this is guaranteed. But nothing is guaranteed what the under lying file write function actually does. So IMO it's implementation-specific. Did you try calling only `fflush`? – Jabberwocky Mar 04 '20 at 09:53
  • @Jabberwocky Yes I tried calling fflush and seems to be working but wanted to know if it is correct way. – Chetan Phadtale Mar 04 '20 at 10:15
  • @ChetanPhadtale what's your platform? Just out of curiosity. – Jabberwocky Mar 04 '20 at 10:16
  • @Jabberwocky This is Move2500 device by Ingenico using Telium Tetra OS. API's are not exactly fflush and fclose but they are GL_File_Flush and GL_File_Close. I don't have knowledge of how they are implemented internally but all other API's provided for this OS work exactly the same as their standard c equivalents. – Chetan Phadtale Mar 04 '20 at 10:21
  • @ChetanPhadtale indeed that's __very__ implementation specific. Maybe you should ask the manufacturer to be sure. – Jabberwocky Mar 04 '20 at 10:23
  • the simple answer: Yes, it is safe to leave the file open. – user3629249 Mar 05 '20 at 08:03

2 Answers2

2

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.

陈敏华
  • 1,365
  • 1
  • 9
  • 9
0

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.

chqrlie
  • 131,814
  • 10
  • 121
  • 189