7

How do I make Delphi write to a text file without erasing the file's previous contents? I already know how to add text but as soon as I try adding more it just replaces the previous text that was already in the file.

I have already tried changing the Rewrite command to Write.

procedure TForm1.BtnokClick(Sender: TObject); 
var 
    myfile :textfile;
    naam, van, adress : string;
begin 
     adress := edtadress.Text;
     van:= edtvan.Text;
     naam := edtnaam.Text; 
     AssignFile(myfile,'C:\test.txt');
     write(myfile);
     Writeln(myfile,naam);
     writeln(myfile,van);
     writeln(myfile,adress);
     closefile(myfile);
end;
5
  • 3
    You'd need to use Append instead of Rewrite. Commented Jun 13, 2014 at 10:18
  • 2
    Do you have any code? Are we able to see it? Commented Jun 13, 2014 at 10:18
  • procedure TForm1.BtnokClick(Sender: TObject); var myfile :textfile; naam, van, adress : string; begin adress := edtadress.Text; van:= edtvan.Text; naam := edtnaam.Text; AssignFile(myfile,'C:\test.txt'); write(myfile); Writeln(myfile,naam); writeln(myfile,van); writeln(myfile,adress); closefile(myfile); Commented Jun 13, 2014 at 10:23
  • I am new to this so i am not really sure how to post coding. Commented Jun 13, 2014 at 10:25
  • You post it in the question rather than a comment Commented Jun 13, 2014 at 10:26

2 Answers 2

15
Uses IOUtils;

...

TFile.AppendAllText(filename, sometext);

Unless you're working with a really ancient Delphi version. http://docwiki.embarcadero.com/VCL/XE/en/IOUtils.TFile.AppendAllText

It also lets you specify an encoding as a parameter

Sign up to request clarification or add additional context in comments.

3 Comments

If the poster has included code indicating that the old style IO (AssignFile, etc.) is being used already, clearly IOUtils and TFile is not the relevant solution. :-)
@kenwhite: That code was not there in the original question... And it's not too late to modernize. :)
Your answer was added 17 minutes ago, and the code was added 2 hours ago. :-) The problem is that the poster is clearly not familiar with Delphi, so they could try to simply add your code to their existing code, which clearly won't work. It's great to encourage modernization, but you have to a) address the existing question first, and b) explain why they should change and clearly show how to do so.
12

Call Append to move to the end of the file:

AssignFile(myfile, filename);
Append(myfile);
Write(myfile, sometext);
....

Please refer to the documentation. In particular this code example: http://docwiki.embarcadero.com/CodeExamples/en/SystemAppend_(Delphi)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.