USING A FILE IN PASCAL
Files are referred to in Pascal programs by the use of filenames.
You have already used two default filenames, input and output.
These are associated with the keyboard and console screen. To
derive data from another source, it must be specified in the
program heading, eg,
program FILE_OUTPUT( input, fdata );
This informs Pascal that you will be using a file called fdata. Within the variable declaration section, the file type is declared, eg
var fdata : file of char;
This declares the file fdata as consisting of a sequence of characters. Pascal provides a standard definition called TEXT for this, so the following statement is identical,
var fdata : TEXT;
BASIC FILE OPERATIONS
Once the file is known to the program, the operations which may
be performed are,
PREPARING A FILE READY FOR USE
The two commands for preparing a file ready for use in a program
are RESET and REWRITE. Both procedures use the name
of the file variable you want to work with. They also accept a
string which is then associated with the file variable, eg
var filename : string[15]; readln( filename );
READING AND WRITING TO A FILE OF TYPE TEXT
The procedures READ and WRITE can be used. These procedures also
accept the name of the file, eg,
writeln( fdata, 'Hello there. How are you?');
writes the text string to the file fdata rather than the standard output device.
Turbo Pascal users must use the assign statement, as only one parameter may be supplied to either reset or rewrite.
assign( fdata, filename ); reset( fdata ); rewrite( fdata );
CLOSING A FILE
When all operations are finished, the file is closed. This is
necessary, as it informs the program that you have finished with
the file. The program releases any memory associated with the
file, ensuring its (the files) integrity.
CLOSE( fdata ); {closes file associated with fdata}
Once a file has been closed, no further file operations on that file are possible (unless you prepare it again).