1

I found some legacy company code that was using an std::fstream and calling fs.flush() after each write, then fs.sync() each time a certain amount of data were written to the stream. This code only needs to do output operations, not input ones.

std::fstream fs(filename, ios::out | ios::binary);
fs.write(buff, size);
fs.flush();
if (/* needs to sync */) {
  fs.sync();
}

This is surprising me as I usually use std::ofstream for output-only IO operations and because this class actually does not have the sync() method.

Since std::ofstream does not have the sync() method, does it makes sense to use std::fstream and sync() for output-only IO operations?

In my specific case, should I keep using std::ofstream and call flush without thinking about sync?

A. Gille
  • 912
  • 6
  • 23
  • _calling fs.flush() after each write_ Does it have a reason for doing that? It will kill performance. – Paul Sanders Dec 02 '20 at 19:15
  • @PaulSanders The code writes a block (buffer) of 8192 bytes at each iteration. I believe that flushing after each write is to ensure that the maximum of data is stored to avoid loss. But then it still does not really makes sense since the file would end-up partially written anyway. – A. Gille Dec 03 '20 at 08:46

1 Answers1

2

If you look at http://www.cplusplus.com/reference/fstream/fstream/ you will find sync under the heading "Public member functions inherited from istream" and its description is:

Synchronize input buffer

Synchronizes the associated stream buffer with its controlled input sequence.

So no, this is not needed for output-only code and will do nothing useful there.

If from the logic of the code it thinks it is doing a fsync equivalent, you would need to do that in a different way. See How to do fsync on an ofstream?

  • This was my understanding too but the code was confusing – A. Gille Dec 02 '20 at 19:16
  • 1
    http://www.cplusplus.com/reference/istream/istream/sync/ <- I think `sync` is throwing away currently unprocessed characters in the input, in any case, nothing you would need for writing –  Dec 02 '20 at 19:18