Search code examples
delphifile-iodelphi-7tstringlist

Delphi Tstringlist, write file synch


I make a very simple log with tstringlist. I write it to file:

pLog.SaveToFile(FileName);

Somewhere there is a bug, and my computer is shut-down. After, I cannot find my log file. Probably the file is saved in asych mode. There is a way for waiting for the write before to go on with the execution?

Thanks, Alberto


Solution

  • If the savetofile call is at the program end, and the program terminates abnormally, then this call probably won't execute. I use a logging mechanism which for every log call opens the log file, writes the log text and time, flushes and then closes the log file. This way, the log text is guaranteed to be written to a file, even if the program terminates abnormally.

    Here's the code:

    procedure TMainForm.Log (const s: string);
    var
     f: textfile;
    
    begin
     assignfile (f, logfilename);
     {$I-}  // yes, I know: modern programming style requires a try/except block
     append (f);
     if ioresult <> 0 then rewrite (f);
     {$I+}
     writeln (f, datetostr (now), ' ', timetostr (now), ' ', s);
     flush (f);
     closefile (f);
    end;