How to declare a file
The first thing you need to know about files is how to declare them in pascal. A file is declared similarly to any other variable like so...
< file variable > :
< type >...
in the declaration will by any of the predefined types or oneof your types that you have defined in the
section. The mostcommon type to use is a record which you have declared. This meansthat the file will store records of that type. e.g. You could have a filecontaining entries of type
which would have attributes likename, address, phone etc..
This is where you give the file variable that you have declared anassociated file name. It works like so:--
assign (<file variable>,<file name>);
. Now your file variable points to a real file on the drive. This is whereall the information will be written to. Now you must open your file.Two ways of opening a file are explained below.
If the file name you have assigned to your file variable does notactually exist on disk then Rewrite will create it for you. What rewritedoes, is clear the file so you can write to it. NOTE: You are not able to
from the file when using rewrite. Rewrite is used like this:--
rewrite (<file variable>);
Easy! Now you can write to the file.
This is a mode where you can both read
write to the file. This is themain mode that you should use in your programs. Sometimes a trick if you want to create a file and have it open for reading and writing is tocreate the file with rewrite and then use reset on the file. Reset workslike so:--
reset (<file variable>);
command closes a file. (as if you hadn't guessed). You needto do this at the end of your program because it saves the changes to thefile. To close a file you write :--
close (<file variable>);
Writing records to a file
Writing records to a file is VERY easy. For the examples coming up wewill be using the following
Now lets say that you have taken input from the user and have all of thevalues of a
variable. Now you want to write it to the file right?To do this you use the
statement. You should notice that this isthe same command that is used for writing to the screen. Well, writingto a file is not much different. All you need to do is the following...
write (<file variable>,person);
You can write as many records to the file as you like now :)