[fpc-pascal] FreePascal Windows - Force files to write to disk

Karoly Balogh (Charlie/SGR) charlie at scenergy.dfmk.hu
Wed Mar 22 13:50:45 CET 2017


Hi,

On Wed, 22 Mar 2017, James Richters wrote:

> No, it is not only freepascal, but not every program either.

I'm no Windows expert, but Windows API seems to have a way do to this
directly. CreateFile() API seems to have a flag, which has a value
FILE_FLAG_WRITE_THROUGH, which will cause the file not go through the
write cache, but gets written directly to the underlying disk, without
delays.

However, this obviously has performance implications on write (will be a
lot slower), and as the documentation notes, it's not supported on every
hardware or file system. Also, I'm not sure if you can do this somehow
together with Free Pascal's file handling API, or you have to restrict
yourself to using direct Windows API calls entirely for writing this file.

Relevant MSDN page:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx#caching_behavior

However, please note that transactional file handling on power loss is a
quite delicate scenario, so you might not be able to solve all the related
problems with this - what happens exactly when you get a power loss during
a write, might be matter of pure luck.

The usual way to work this problem around on Linux systems at least, is to
write a new file, then do an overwriting rename to the old file name.
There rename is an "atomic" operation, which will be either committed to
the disk or not, but if it was unsuccessful, you won't end up with
half-written files. But IIRC Windows didn't support atomic renames. Maybe
someone with more Windows knowledge will fix me. You definitely don't want
to implement a copy though, and that's anything but atomic.

Charlie



More information about the fpc-pascal mailing list