简体   繁体   中英

How to append to text file in Delphi?

I am designing a program that writes to and stores data in a text file. The problem is that whenever I enter new data into the file, the old data is cleared and just that one entry (line) is there. I was originally saying Rewrite(tFile) every time but now use a boolean to check if the text file has been rewritten. I still get the same problem..

    begin
    AssignFile(tNotifications, 'Notifications.txt');
    if bRewritten = False then
      begin
        Rewrite(tNotifications);
        bRewritten := True;
      end;
     Writeln('test');
     CloseFile(tNotifications);

After AssignFile() you must make a choise, whether to Reset to read the file, or if you are going to write to the file, whether to Append to the file or Rewrite the file.

If you want to retain existing data in the file and just append additional data, then you call Append() .

If you want to replace existing data in the file with new data, then you call Rewrite .

I don't understand what the purpose of your boolean bRewritten is, I would expect you to set it somewhere else in your program as a signal for the file writing routine to either call Append() or ReWrite() .


In an answer to an earlier question it was suggested to use a TStringList and its SaveToFile() method. If you would use TStringList and you would want to append, you would first read the file ( StringList.ReadFromFile() ), add new strings to the StringList and finally save ( StringList.SaveToFile() ). To rewrite the existing file you would just omit the reading before adding strings to the StringList and saving.

I support using a TStringList as a modern and more convenient solution.

Oldstyle solution (have you looked at See Also section in AssignFile help?):

AssignFile(tNotifications, 'Notifications.txt');
Append(tNotifications);
Writeln(tNotifications, newtext);

For fresh Delphi versions ( help ):

add IOUtils to uses
...
TFile.AppendAllText('Notifications.txt', newtext);  

Or examine "append". Btw: AssignFile can be substituted by the more correct Assign.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM