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

Tomas Hajny XHajT03 at hajny.biz
Tue Feb 21 22:56:38 CET 2017


On Tue, February 21, 2017 22:12, James Richters wrote:


Hello James,

> I have a freepascal Windows console application that I recently ported
> over from DOS Turbo Pascal.   I am have a small settings file that I write
> to disk that keeps getting corrupted.  It happens only occasionally, but
> it’s always this one file, no others.    Do I need to do something
> specific to force windows to write the file to disk and not have it in
> some kind of cache or buffer?   I am using the following code to write the
> file:
>
>    Assign(BitFile,'BitSave.pax');
>    ReWrite(BitFile);
>    WriteLn(BitFile,XADJ:1:8);
>    WriteLn(BitFile,YADJ:1:8);
>    WriteLn(BitFile,ZADJ:1:8);
>    WriteLn(BitFile,WADJ:1:8);
>    WriteLn(BitFile,AADJ:1:8);
>    WriteLn(BitFile,TADJ:1:8);
>    WriteLn(BitFile,VADJ:1:8);
>    WriteLn(BitFile,UADJ:1:8);
>    WriteLn(BitFile,CurrentTool);
>    WriteLn(Bitfile,P_Value[4]);
>    Close(BitFile);
>
> The above only happens when I make a change to one of the settings, and
> the system is never having any issue at that time, yet upon occasion I
> will have an error opening the file and when I inspect it, it’s just a
> long string of [nul].   I am not leaving the file open, I’m assigning it,
> writing to it, then closing it, so there should be no opportunity for data
> to be lost.  I am having the same issue on about 8 different computers,
> most of which are running solid state hard drives. It’s always just this
> one file that is affected, nothing else.  No other process ever uses this
> file, so it must be my freepascal program that is leaving the file in a
> vulnerable state.

It's difficult to find out possible reasons without fully compilable
source. If I should guess, I would check the types of the variables used
for writing and also make sure that the content of those variables isn't
overwritten in memory (i.e. even before they're written to the file). In
particular, if your variables are strings and you compiled the source
(originally written for Turbo Pascal, i.e. using shortstrings) e.g. with
{$H+}, or in a compiler mode using ansistrings or
widestrings/unicodestrings by default _and_ the original source modified
the strings in a non-standard way, you might overwrite the content of
those variables.

BTW, what exactly is the error you get when opening the file?


> My understanding was the Close(file); would save the file all the way to
> disk and flush any buffers that were holding it, but I’m wondering if that
> was only true for DOS and there is some other windows cache or buffer that
> also needs to be instructed to flush to truly save the file all the way to
> disk and close it.

Your understanding is correct, nothing else should be necessary.

Tomas





More information about the fpc-pascal mailing list