Home > Mobile >  what is practical differences between flush, write() and fflush()?
what is practical differences between flush, write() and fflush()?

Time:12-07

In this post, the answer said

Flushing: To sync the temporary state of your application data with the permanent state of the data (in a database, or on disk).

I think that the flush is executed when some buffer is written to an i/o device (like disk) by the write() system call.

So it seems that a data writing to a device with write() and the data flushing to the device are to do the same things.

If so, can I say that the flushing a data with fflush() and the writing the data with write() are completely same?

CodePudding user response:

Flushing and writing are similar in that they both involve transferring data from a temporary storage location (such as a buffer in memory) to a more permanent location (such as a file on disk). The key difference between the two is that flushing only refers to the act of moving data from the buffer to the destination, while writing also includes the act of placing the data into the buffer in the first place.

The fflush() function is used to flush the output buffer of a stream. This means that any data that has been written to the buffer but not yet transferred to the underlying device (such as a file on disk) will be moved to the device. In other words, fflush() ensures that any data in the buffer is actually written to the destination.

In contrast, the write() function is a low-level system call that is used to write data to a file. When you use write(), you specify the data that you want to write, as well as the destination file where the data should be written. The write() function then writes the data directly to the file, bypassing any intermediate buffer.

So, to answer your question: no, fflush() and write() are not the same. fflush() is used to flush the output buffer of a stream, while write() is used to write data directly to a file.

CodePudding user response:

First, let's do the obvious thing:

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.

The C Standard doesn't state how the data is written to the output device. On Posix systems, most likely via write, other systems might have different (similar) interfaces.

Conceptually speaking, a flush will use the underlying write primitive to transmit the data from the buffer to the output device.

In short:

  • fflush() the same as write() -> No.
  • fflush() uses write() -> Yes, most likely.
  • fflush() and write() ensures the data to be written to the output device -> Yes.
  • Related