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);
  F: TextFile;
  AssignFile(F, 'C:\Test\Data.txt');
  WriteLn(F, Edit1.Text);
  WriteLn(F, Edit2.Text);

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);
  F: TextFile;
  S: string;
  if FileExists('C:\Test\Data.txt') then begin
    AssignFile(F, 'C:\Test\Data.txt');
    ReadLn(F, S);
    Edit1.Text := S;
    ReadLn(F, S);
    Edit2.Text := S;
    ShowMessage('File C:\Test\Data.txt not found');



DC Library  FAQ
Crash Course Delphi  Tips  Source Code  Downloads  Links 

Copyright 1999-2019