At what point is the actual recording of information on the disc?

There is, for example, the following code:

std::ofstream file("somefile"); file << "Hello, world!\n"; std::flush(file); 

If immediately after executing the line std::flush(file) I cut down electricity, then what are the chances when it is turned on to see in the file Hello, World! ? If the chance is not 100%, then how to bring it to the desired guarantee result? Does the OS (Linux / Windows) have any way to make sure that the information on the disk has entered? How is this situation handled in databases during transactions?


UPD: Will the line be written to the file if the program crashes right after std::flush(file) ?

  • Here, for example, I do some record in a DB transactionally. The DB should return to me that transaction successfully. To do this, the database must know at what point the transaction is written to disk / log / log, so that you can recover from this data later. And about the bespereboynik - the question is no longer in them, but in the theoretical situation of the failure of the computer with the system so that the drive will live - Andrei Kurulev

1 answer 1

Except when the file was opened with the O_SYNC system's O_SYNC flag (read about all its flags will probably be useful anyway), fflush() does not provide the functionality you want.
This function moves data from the buffer associated with a file in user space to the buffer cache in kernel space.

To force synchronization with the device when working with FILE * after fflush you need to make an fsync system call (for example, fflush(file), fsync(fileno(file)); ), which synchronously writes the file data (and its meta information) to the device, providing popping a device cache, if it exists.

(fsync () transfers ("flushes") can be retrieved even after the system crashed or was rebooted. This includes writing through or flushing a disk cache if present. The call blocks until the device reports that the transfer has completed. It also flushes metadata information associated with the file (see stat (2)).

However, note the following text in the manual (man-e)

Calling fsync () Fsync () for a directory descriptor for the directory is also needed.

which may cause problems for new files.