File handling
Sequential files
Sequential files hold data in a set sequence/order. A programmer may want to use the data that is saved in a sequential file.
File operations
File operations allow programmers to do the following to data in sequential files:
- open
- create
- read
- write
- close
When files are opened, closed or amended, the file management and memory management functions of the operating system will be active.
Open
Open will open a sequential file so that the program can read data from the file or write data to the file.
OPEN english_towns
Create
The Create operation allows for the creation of a new sequential file.
Sometimes the create operation is implicit when the Open operation is used. This means that if the program attempts to open a file that does not exist, it will automatically create a new file.
In this case the file name is english_towns.
CREATE english_towns
Read
Unlike Create, Open and Close there is no Read command used in reference language.
To Read from a sequential file means to take the data from the file and store it in a variable, array or record for future use in the program.
Before you can read from a file you have to open the file. Once the file is open it is possible to create code that will read specific data from the file.
In this example we presume that the file called english_towns contains a sequential list of fifty town names.
OPEN english_towns
FOR counter FROM 0 TO 49 DO
RECEIVE townname [counter] FROM english_towns
END FOR
CLOSE english_towns
Write
Write follows the same principle as read. However, when you write to a file you are often sending the values held in variables, arrays and records out of the program for storage within a sequential file.
This example presumes that the file has just been created and does not yet hold any town names.
The reference language below is designed to write data to a sequential file.
OPEN english_towns
FOR counter FROM 0 TO 49 DO
SEND townname [counter] TO english_towns
END FOR
CLOSE english_towns
Close
Close will close a sequential file when it is no longer needed. This will reduce pressure on RAM as the file will not be held there anymore.
CLOSE english_towns
Different programming languages
Different high level languages will use different syntax for performing file handling operations. While the reference language that you need to be able to read and understand uses the generic terms SEND and RECEIVE, some languages will make use of read and write. Be sure to learn how to implement create, open, close, read and write operations in the language that you are using in class.