Handling Files in Delphi - Reading from a file
(Page 2 of 4 )
There are two ways to read from a file:
- Line by line
- Reading the entire contents into a string list.
Line by line
To read the file line by line we need to open the file for input by calling the reset procedure:
var
Afile : TextFile;
buffer : string;
begin
AssignFile(Afile, 'notes.txt') ;
try
Reset(Afile);
ReadLn(Afile, buffer) ;
Memo2.Lines.Add(buffer) ;
finally
CloseFile(Afile) ;
end;
end;
There are two types of read procedures, readln and read. The difference is that Readln moves to the pointer to the next line after reading and Read does not. Here's how you would read from a file using Read procedure:
var
Afile : TextFile;
buffer : string
begin
AssignFile(Afile, 'notes.txt') ;
try
Reset(Afile);
Read(Afile, buffer) ;
Memo2.Lines.Add(buffer) ;
finally
CloseFile(Afile) ;
end;
end;
Reading the entire contents of a file
Double click on the "read from file" button and add the following code:
procedure TForm1.Button2Click(Sender: TObject);
begin
Memo2.Lines.LoadFromFile('notes.txt');
end;
We use tmemo's loadfromfile() procedure to load the entire contents of a file.
Next: Binary Files >>
More Delphi-Kylix Articles
More By Jacques Noah