delphifreepascallazarus

Lazarus/Delphi – writing to text file without overwriting next time


I’m using Lazarus and I wanted to save information to a text when the program terminates. But each time I reopen the program it overwrites what was there before in the text file. It would be OK to append a new line to the file or even create a different text file each time. This is what I have:

var
  // … other variable declarations omitted …
  s: TStringList;
begin
  s:= TStringList.Create;
  s.Add(datetostr(now));
  s.SaveToFile(datetostr(now)+'.txt');
  s.Free;

But it gives me an error.


Solution

  • All you need to do is open your file in append mode, and then add your text. It will put the new data at the end of the file:

      AssignFile(tfOut, C_FNAME);
    
      try
        // Open for append, write and close.
        append(tfOut);
    
        writeln(tfOut, 'New data for text file');
        writeln(tfOut, 'New informtion should be at the end of the file.');
    
        CloseFile(tfOut);
    
      except
        on E: EInOutError do
         writeln('File error. Elaboration: ', E.Message);
      end;