Delphi source code

Writing and reading to/from a text file


For saving one or more strings to a text file, you code the following steps:

  1. Declare a variable of the type TextFile.
  2. Use the command AssignFile to connect the TextFile variable to a physical file on disk.
  3. "Open" the text file for writing with the command Rewrite. This means, that a new text file will be created on the disk. If there is already a file with the same name, it will be overwritten.
  4. Write a string to the file with WriteLn. You can repeat this step as many times as you want.
  5. Finally, "close" the text file with CloseFile.

The example below shows how to save the contents of two Edit-components to a text file C:\Test\Data.txt

procedure TForm1.btnWriteClick(Sender: TObject);
var
  F: TextFile;
begin
  AssignFile(F, 'C:\Test\Data.txt');
  Rewrite(F);
  WriteLn(F, Edit1.Text);
  WriteLn(F, Edit2.Text);
  CloseFile(F);
end;

Reading strings from a text file is very similar, but in order to be on the safe side, you need an extra step. Before trying to read, you have to check if the file exists. You also need an extra variable to receive the strings that you read from the file. This are the steps:

  1. Declare two variables, one of the type TextFile and one of the type String.
  2. If the file exists, continue with step 3. If not, it ends here. Optionally, you can show an error message to the user.
  3. Use AssignFile to connect the TextFile variable to a physical file.
  4. "Open" the text file for reading with the command Reset.
  5. Read a string from the file into the string variable, with the command ReadLn. Repeat this step to read the next line(s) of the file.
  6. Finally, "close" the text file with CloseFile.

Here's an example that loads the contents of the two Edits from the text file C:\Test\Data.txt

procedure TForm1.btnReadClick(Sender: TObject);
var
  F: TextFile;
  S: string;
begin
  if FileExists('C:\Test\Data.txt') then begin
    AssignFile(F, 'C:\Test\Data.txt');
    Reset(F);
    ReadLn(F, S);
    Edit1.Text := S;
    ReadLn(F, S);
    Edit2.Text := S;
    CloseFile(F);    
  end
  else
    ShowMessage('File C:\Test\Data.txt not found');
end;

 

Crash Course Delphi Become member of the DelphiLand Club and get our Crash Course Delphi, plus the fully commented source code of numerous projects, plus guaranteed answers from our Q/A Forum. Membership is for life!

TOP   DelphiLand Club Membership  DC Library  Forum  Forum Archives
Crash Course Delphi  Tips  Source Code  Downloads  Links 

© Copyright 1999-2016 
Studiebureau Festraets