Handling Files in Delphi
(Page 1 of 4 )
Handling files in Delphi is not so different from handling files in any other high level programming language. In this article we will examine how to read and write to text files and binary files and we will also explore various methods of accessing files.
Downloadable files for this article are available
here and
here.
Required
Borland Delphi, any version.
Text Files

Example file handling program..
In short, text files contain readable ASCII characters. The text within a text file is characterized by lines that are terminated by end-of-line characters.
To open a text file, we need to link a file that is on the local disk with a variable in our code. We do this by using the AssignFile() method. First declare a variable of type text file and then assign that variable with a file on your disk through the AssignFile() procedure.
Example:
var Afile:textfile;
begin
AssignFile(Afile,Afilename);
...
end;
Once you've associated the file with a variable, you are now free to read and write to this file by referring to it by its variable name: Afile. Once you have finished reading and writing to that file, you call the closefile(Afile) procedure to signal that you have finished using the file.
Enough of the theory, let's write to an example file:
In Delphi, create a new application and add two tmemo components. Then add two buttons with the captions Write to File and Read from File, respectively.
Double click on the "write to file" button and add the following code:
var
Afile:textfile;
i:integer;
begin
if memo1.lines.Text = '' then begin
showmessage('Please enter some text');
end
else begin
assignfile(Afile,'notes.txt');
try
rewrite(Afile);//create this file if it does not exist,
otherwise open it.
for i:= 0 to (-1 + Memo1.Lines.Count) do
WriteLn(Afile, Memo1.Lines[i]) ;
finally
closefile(Afile);
end;
end;
end;
Also, try to use the try/finally blocks for exception handling, as I/O can be full of surprises. The rewrite procedure creates a new file and moves the file pointer to the beginning of the file. If a file with the same name already exists, it is deleted and a new empty file is created in its place. So if you do not want to lose the data in a file, but want to add some data to it, you use the append() procedure.
Append procedure
The append procedure enables you to add data to an existing file. To demonstrate, add another button and a memo to our application. Double click on the button and add the following code:
procedure TForm1.Button3Click(Sender: TObject);
var
Afile:textfile;
S:string;
begin
AssignFile(Afile,'notes.txt') ;
try
Append(Afile) ;
s:=memo3.Lines.Text;
Writeln(Afile,s);
finally
CloseFile(AFile) ;
end;
end;
The append procedure positions the file pointer at the end of a file.
Next: Reading from a file >>
More Delphi-Kylix Articles
More By Jacques Noah