For saving one or more strings to a text file, you code the following steps:
- Declare a variable of the type TextFile.
- Use the command AssignFile to connect the TextFile variable to a
physical
file on disk.
- "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.
- Write a string to the file with WriteLn. You can repeat this step as
many
times as you want.
- 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:
- Declare two variables, one of the type TextFile and one of the type
String.
- If the file exists, continue with step 3. If not, it ends here. Optionally,
you
can show an error message to the user.
- Use AssignFile to connect the TextFile variable to a physical file.
- "Open" the text file for reading with the command Reset.
- 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.
- 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;
|
|