Search code examples
delphidisk-io

Delphi IOresult misbehaving


I have an application that saves data to an xml file but when data cannot be interpreted it writes a message to a textfile. I am using Delphi 11, Windows 10, 64bit compilation The procedure to write the message looks like this (Of course the NamedOPFile was created elsewhere and mostly works)

procedure WriteStrToNamedOPFile(var NamedOPFile: TextFile; TextString: string);
begin
{$I-}
  append(NamedOPFile);
{$I+}
  if IOResult = 0 then
  begin
    System.writeln(TextFile(NamedOPFile), TextString);
    closefile(TextFile(NamedOPFile));
  end
  else
    ShowMessage('LOG File write access error: IOResult = ' + inttostr(IOResult));
end;

Every now and then (ie not always) I get the following error message

LOG File write access error: IOResult = 0<

Which should not be possible as the IOResult is 0.

Could this be a timing issue to disk or something else?


Solution

  • Accessing IOResult resets its value to 0. The proper way to do it would be more like this:

    procedure WriteStrToNamedOPFile(var NamedOPFile: TextFile; TextString: String);
    var
      Res: Integer;
    begin
    {$I-}
      Append(NamedOPFile);
    {$I+}
      Res := IOResult;
      if Res = 0 then
      begin
        System.Writeln(TextFile(NamedOPFile), TextString);
        CloseFile(TextFile(NamedOPFile));
      end
      else
        ShowMessage('LOG File write access error: IOResult = ' + IntToStr(Res));
    end;