Delphi provides a number of different file access
mechanisms. The oldest is in support of consoles, where the Read, ReadLn,
Write and WriteLn routines have a syntax that omits the file name.
With no file name, IO (Input and Output) is routed to the console.
A D V E R T I S E M E N T
Of greater importance to modern applications, are disk file operations. Disks
such as hard disks, floppy disks, CDs and DVDs (the latter are treated as read
only).
Delphi confusingly provides two basic sets of routines for file handling. The
most Delphi like are covered by this article and this web site. The other type
are thin wrappers around Windows APIs - and as such are platform specific. They
also support text files less intuitively. They are not covered here.
Additionally, hidden away, Delphi provides a very elegant way of reading and
writing complete text files. The
TStringList
class has methods for loading the list of strings from a text file. And for
saving the list likewise. See the final section of this article.
Accessing files
There are a number of basic operations for handling both text and binary
files. (The latter can hold non character data values). First, we must get a
handle for a named file:
var
myFile : TextFile;
begin
AssignFile(myFile, 'Test.txt');
Here we are getting a handle to a text file, designated by the TextFile
type (binary files are of type File). We ask Delphi to assign a file
handle for a file called 'Test.txt' which will be assumed to be in the
current directory (as given by the
GetCurrentDir
routine).
Next, we must open the file using this handle. This operation tells Delphi how
we want to treat the file. There are 3 ways of opening the file:
ReWrite
Opens a file as new - discards existing contents if file exists
Reset
Opens a file for read and write access
Append
Opens a file for appending to the end (such as a log file)
We'll cover the access mechanisms for text and binary files separately.
Meanwhile, when we have finished, we must close the file:
CloseFile(myFile);
Reading and writing to text files
Text files are great for simple uses,
such as where we record a processing log. Text files fall short when reading and
writing structured data. They do support number to string and string to number
formatting, but you are often better off defining your own record structure and
using a typed binary file instead.
Here is a simple example of access to a text file:
var
myFile : TextFile;
text : string;
begin
// Try to open the Test.txt file for
writing to
AssignFile(myFile, 'Test.txt');
ReWrite(myFile);
// Write a couple of well known words to this
file
WriteLn(myFile, 'Hello');
WriteLn(myFile, 'World');
// Close the file
CloseFile(myFile);
// Reopen the file for reading
Reset(myFile);
// Display the file contents
while not Eof(myFile) do
begin
ReadLn(myFile, text);
ShowMessage(text);
end;
// Close the file for the last time
CloseFile(myFile);
end;
The ShowMessage routine displays the following :
Hello
World
If we replaced the ReWrite routine with Append, and rerun the
code, the existing file would then contain:
Hello
World
Hello
World
since append retains the existing file contents, appending after this anything
new written to it.
Notice that we have used WriteLn and ReadLn to write to and read
from the file. This writes the given text plus a carriage return and line feed
to the text. The read reads the whole line up to the carriage return. We have
read from the file until
Eof (End Of File)
is true. See also Eoln.
We can use Read and Write to read and write multiple strings to a
file. More importantly, we can use these to write numbers as strings, with some
useful formatting for further
details):
var
myFile : TextFile;
text : string;
i: Integer;
begin
// Try to open the Test.txt file for
writing to
AssignFile(myFile, 'Test.txt');
ReWrite(myFile);
// Write a couple of well known words to this
file
Write(myFile, 'Hello ');
Write(myFile, 'World');
// Terminate this line
WriteLn(myFile);
// Write some numbers to the file as a single
line
for i := 2 to 4 do
Write(myFile, i/2, '');
// Terminate this line
WriteLn(myFile);
// repeat the above, but with number
formatting
for i := 2 to 4 do
Write(myFile, i/2:5:1);
// Terminate this line
WriteLn(myFile);
// Close the file
CloseFile(myFile);
// Reopen the file for reading only
Reset(myFile);
// Display the file contents
while not Eof(myFile) do
begin
ReadLn(myFile, text);
ShowMessage(text);
end;
// Close the file for the last time
CloseFile(myFile);
end;
Hello World
1.00000000000000E+00001.50000000000000E+00002.00000000000000E+0000
1.01.52.0
Reading and writing to typed binary files
Typed binary files are files
that have a data type as the basic unit of writing and reading. You write, say,
an Integer, or
aRecord to a
file, and read the same unit of data back. Records are particularly useful,
allowing us to store any mix of data types in the one file unit of data.
This is best illustrated with an example:
type
TCustomer =
Record
name : string[20];
age: Integer;
male : Boolean;
end;
var
myFile : File of TCustomer;//
A file of customer records
customer : TCustomer;// A customer
record variable
begin
// Try to open the Test.cus binary file for
writing to
AssignFile(myFile, 'Test.cus');
ReWrite(myFile);
// Write a couple of customer records to the
file
customer.name := 'Fred Bloggs';
customer.age:= 21;
customer.male := true;
Write(myFile, customer);
// Reopen the file in read only mode
FileMode := fmOpenRead;
Reset(myFile);
// Display the file contents
while not Eof(myFile) do
begin
Read(myFile, customer);
if customer.male
then ShowMessage('Man with name '+customer.name+
' is '+IntToStr(customer.age))
else ShowMessage('Lady with name '+customer.name+
' is '+IntToStr(customer.age));
end;
// Close the file for the last time
CloseFile(myFile);
end;
Man with name Fred Bloggs is 21
Lady with name Jane Turner is 45
The code is very similar to that used for text files, except that we define a
file of a certain type (record), and pass/receive record data when
writing/reading.