1

I want to make sure data is flushed to disk when I call flush.

A simple code example is:

int main() { std::ofstream outfile("test.txt"); for (int n = 0; n < 100; ++n) { outfile << n; outfile.flush(); // TODO: insert code to make sure data is flushed to disk // I tried using the stat file size but it does not always grow after flush. } outfile.close(); return 0; } 

I am sure that std::ofstream properly implements the flush function. In fact I am trying test the flush function of another library and this is just an example.

3
  • 3
    The flush function only flushes the streams buffer. There might be underlying buffers (for example in the operating system or filesystem drivers, or even on the drive itself) that might need to be flushed and synchronized. For this you need to consult the documentation for your operating system. Commented Apr 3, 2020 at 19:26
  • 2
    out of curiosity: why call flush at all ? I wouldnt want to flush the file inside the loop Commented Apr 3, 2020 at 19:27
  • @idclev463035818 this is just an example for testing flush. Not intended to be used in practice. Commented Apr 3, 2020 at 19:37

1 Answer 1

2

outfile.flush() will flush the stream buffer to the operating system. If you want to make sure the system buffers are flushed to disk, you must issue an OS specific system call to do that. On POSIX compliant systems, you can call sync() defined in <unistd.h>.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.