When you write a program computing many values for later use, you want
a way to store them permanently, since an array can store values but not
permanently and you loose the computed values. Instead of always beginning
from the very beginning, you could use files to store your data permanently,
it is not lost even if you turn off your computer and stays there until
you decide to remove it. Isn't this marvellous?
Now, the logic of files should be explained:
-
First of all you have to specify the type of the file, what type of values
should the file store. For this you declare either a type or use it directly
in the variable declaration part. This is done by using filevariablename
: file of datatype, where datatype could be any type you have
declared before or any ordinal datatype. If you want your data file to
store only characters, that is just plain text, you can define its type
as text, that is filevariablename : text.
-
Then, you have to assign a name to the file which is to be used to store
data. This is done by using : assign(filevariablename,'path
of file'), where path of file could be directly a filename such
as data.txt with a at most 3 letters long extension or it could be the
whole path to it, soecifying which drive, which directory and which file
name.
-
If you want to write to a file, you have to prepare it for this operation
by using rewrite : rewrite(filevariablename);
-
If on the other hand you want to read from a file data already stored,
you should prepare the file for input using reset. reset(filevariablename);
-
Reading from a file is the same as reading from the terminal, except that
you have to specify the sourcefile to the read function. read(filevariablename,a);
where a is of the datatype which is stored in the file to be read, otherwise
you will get a compilation error.
-
Writing to a file is just as writing to the screen, but you have to supply
the filename. writeln(filevariablename,a), where
a has the same type as the data stored in the file, otherwise you will
get a compilation error.
-
At the end of the program, after everything is done to the file, you have
to close the file again by writing close(filevariablename).
Important note: You
can check whether you arrived at the end of a line in the textfile during
read as eoln(filevariablename),
or
end of file by using eof(filevariablename).
Example:
Displaying the content of the file onto the screen:
program echofile(input,output); |
var |
f:text; |
ch:char; |
begin |
assign(f,'echo.txt'); |
reset(f); |
while not eof(f) do |
begin |
read(f,ch); |
write(ch); |
end; |
close(f); |
end. |