I couldn't do it. I ended up going to storing my data in several
different files. Backups are written 30 seconds later. Buffers are
flushed. Even with this, very occasionally both primary and backup will
be corrupted. My software has to cope with this automatically so worst
case is recent data is lost.
Flushing buffers may not be enough: by default the buffers are flushed to
the OS, but the OS may still cache them for later writing.
There are three ways to ensure that flushing really goes all the way to
disk:
- using the _commit() low-level IO function
- adding the 'c' flag to the mode parameter in fopen()
- link the program with "commode.obj", which makes 'c' flag the default.
This is easily overlooked by people who "already know" C/C++ because
neither possibility exists in the ISO standard variety.
When you're using low level IO, _commit is supposed to force immediate
flushing of a file to disk.
http://msdn2.microsoft.com/en-us/library/17618685.aspx
Standard C fflush() or flushall() will flush a stream's data to the OS, but
don't guarantee by default that the physical write has occurred before the
call returns.
http://msdn2.microsoft.com/en-us/library/c565h7xx.aspx near the end of the
page:
"Use fflush or _flushall to ensure that the buffer associated with a
specified file or all open buffers are flushed to the operating system,
which can cache data before writing it to disk. The commit-to-disk
feature ensures that the flushed buffer contents are not lost in the event
of a system failure."
The "commit-to-disk" feature is activated by the 'c' flag in fopen (for
example "w+c" instead of "w+"), or linking the program with "commode.obj".