Search code examples
pascallazarusfreepascaldelphi

lazarus / delphi (pascal) - writing to txt file without overwriting next time


I'm using lazarus and I wanted to save to a txt file, information when the program is closed. But each time i reopen the program it overwrites what was there before in the txt file. It would be ok both to write to the next line or even creating a different txt file each time. This is what i have:

var
  ...
  s: TStringList;

  s:= TStringList.Create;
  s.Add(datetostr(now));
  s.SaveToFile(datetostr(now)+'.txt');
  s.Free;

but i'ts giving 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;