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
?
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?