Chapter 8
FILES
Until now, all data in our programs has been stored in the computer's
memory. Data can also be stored in files. This chapter will show how to
use text files to store program data, and how to retrieve this data.
Data in a text file can be thought of as a sequence of characters stored
in a sequence of lines. Each line has an end-of-line (EOLN) marker after
it. Each line has an end-of-file (EOF) marker after the last line in the
file.
To access a text file, the file's name must be associated with a variable
of type TEXT. This requires two steps. First, a variable of type TEXT must
be declared. Second, the filename must be associated to the variable using
the ASSIGN statement.
The file must also be opened to access it. When the program finishes
accessing the file it must be closed. The RESET, REWRITE, and CLOSE keywords
are used for this purpose.
Program Intro_to_Files (input, output);
{This program opens a file }
{and writes some text to it}
var
My_File : text;
Begin
{associate data.txt to the}
{ variable My_File}
Assign(My_File, 'c:\data.txt');
Rewrite(My_File); {open the file}
{write to My_File}
Writeln(My_File, 'First line');
Writeln(My_File, 'second line');
Close(My_File);
End.
The first statement in the main program associates the filename with
the file variable. The second statement opens the file for output. The third
line writes to the file. Notice that the name of the file is the first argument
that is passed to the Writeln statement. After writing to the file the close
statement closes the file.
The following program will read the output from the previous program.
It will use a loop to read the file character by character
Program Intro_to_reading (input, output);
var
My_File : text;
ch : char;
Begin
Assign(My_File, 'c:\data.txt');
Reset(My_File); {open the file for input}
Repeat
Repeat
{read a single character from the file}
read(My_File,ch);
write(ch); {display it}
{keep looping until it reaches the EOLN}
Until EOLN(My_File);
{move to the next line}
Readln(My_File,ch);
{write to the next line}
Writeln;
{keep looping until it reaches the EOF}
Until EOF(My_File);
End.
 |