5

We have a logger in our library that writes lines of text to disk for later diagnosis. We use it for many purposes including analyzing hard machine hangs caused by the application or our library.

We would write a line to the log file then call fclose(), then reopen it for append when we need to write another line. This is 35X slower than calling fflush() after writing a line.

So my question is, am I more likely to have the last line successfully stored in the file with the fclose() approach than the fflush() approach? If so, why? If not, what is that 35X larger amount of time busy doing if not writing the data more safely to disk?

We care the most about Windows, by the way.

3
  • 1
    Some data might remain in the page cache and not yet written to the disk. There is no much to do about that in practice (at reasonable cost; on Linux you don't want to call sync(2) at every line...). To avoid losing data, send it on the network (e.g. with syslog(3)...) There is no failproof solution... Sep 25, 2015 at 4:52
  • 1. Disk is working in blocks 6/8/16KB and more (and operations if FAT/other management tables). close/open must all this buchaltery. 2. fflush give high hope all be written on disk, may be buffered in low-level procedures. Linux C code use fctl() or sync() to really synt this low lewl buffers. - but code must wait few ms because to disk move .
    – Jacek Cz
    Sep 25, 2015 at 4:52

2 Answers 2

5

From http://en.cppreference.com/w/c/io/fflush:

For output streams (and for update streams on which the last operation was output), writes any unwritten data from the stream's buffer to the associated output device.

I would say fflush should work for your needs.

1
  • 3
    fflush() flushes user mode buffers to the OS. fsync() flushes the OS buffers to disk. It would be prudent to do both (if performance is acceptable).
    – keithmo
    Sep 25, 2015 at 7:05
4

Opening and closing a file for each write operation is not a optimal solution. File opens are costly operation. Also, fclose() would not guarantee that file data is flushed to the disk immediately on closing the file. The OS/filesystem will flush the data on their own logic.

fflush() will flush any data written to a file and is not yet synced to the disk. However, note that is will try to flush all blocks of file, not just latest blocks written. So if its big file and multiple applications writing to it, all of their data is flushed. However, doing flush for every write can be inefficient.

So if you really want your data to be written immediately use direct IOs, which will write data directly to the disk. And if you want to make this efficient, make them asynchronous.

1
  • What do you mean by "direct IOs" ? Apr 21, 2023 at 23:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.