-3

I was reading http://www.cplusplus.com/reference/cstdio/fflush/ and I was curious about what it means. According to the website it says:

If the given stream was open for writing (or if it was open for updating and the last i/o operation was an output operation) any unwritten data in its output buffer is written to the file.

What does the output buffer to file mean?

Storm
  • 17
  • 3

2 Answers2

4

Some streams buffer output data and do not write to the device immediately. fflush forces the contents of the stream's buffer, if there is one, to be written to the device and the buffer cleared.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 4
    Might be worth mentioning that by default, `stdout` is line buffered (will flush after newlines), and `stderr` is unbuffered. – Kerrek SB May 22 '14 at 23:10
2

Generally, when data is intended to be written to a file, it is stored in a construct known as a "buffer". Once the buffer has reached a certain threshold, all the data stored in the buffer will be written out to the file at once.

Fflush empties the buffer and forces all changes to be written to the file. This is particularly useful when you are done writing to the file, since it is good practice to flush the buffer before closing the file (thereby making sure that all data has been successfully written to the file).

This goes for other types of filestreams too.

  • 5
    `fclose` flushes the buffer; calling `fflush` yourself before closing is redundant. I don't really think its a 'best practice'. – Colonel Thirty Two May 22 '14 at 22:55
  • 1
    I got to agree with @ColonelThirtyTwo, it irks me when people do it, the same with checking for `NULL` before calling delete on a pointer... – AliciaBytes May 22 '14 at 22:59