Do you know what happens to the variables, arrays, constants that you create in your programs when you close them?
Well, they simply lose all the values that you or your program assigned to them.
If you do not want to lose all those values then you need to use files.
Files provide a method by which we can store the outputs of the program before they are lost.
Some of the benefits of using files for storage are:
Reusability: the output saved and stored on a file can be imported back into programs, thereby making them reusable.
Large storage capacity: unlike arrays or variables, files can be used to store relatively large capacity of data.
Portability: data stored on files allows for it to be shared with others as a file, or exported into a different format to be used on other systems.
The three operations that files allow you to do are:
Open
Process (read/write)
Close
Syntax:
OPENFILE <nameOfFile> FOR <File Mode>
The file modes are:
READ
WRITE
Example
Open the file dinosaurs.txt to output all its contents on screen.
Solution:
OPENFILE dinosarus.txt FOR READ
When processing files we say we are using them in a mode. The following file modes are used:
Read
Write
Data is read from the file, only after the file has been opened in READ mode using the READFILE command as follows:
READFILE <nameOfFile>, <variable>
When the command is executed, the data item is read and assigned to the variable.
Data is written into the file after the file has been opened using the WRITEFILE command as follows:
WRITEFILE <nameOfFile>, <variable>
When the command is executed, the data is written into the file.
Files should be closed when they are no longer needed using the CLOSEFILE command.
Syntax:
CLOSEFILE <nameOfFile>
Examples
This example uses the operations together, to copy a line of text from FileA.txt to FileB.txt.
Solution:
DECLARE lineOfText : STRING
OPENFILE FileA.txt FOR READ
OPENFILE FileB.txt FOR WRITE
READFILE FileA.txt, lineOfText
WRITEFILE FileB.txt, lineOfText
CLOSEFILE FileA.txt
CLOSEFILE FileB.txt
Write an algorithm that creates a file called contacts.txt, and store the name and surname of your friends. The file should look like this:
Oscar Taylor
Riduan Clancy
Patrick Gonzalez
Charlie Fernandez
Solution:
OPENFILE contacts.txt FOR WRITE
OUTPUT "How many friends are you going to record?"
INPUT numberOfFriends
FOR count ← 1 TO numberOfFriends
INPUT name
INPUT surname
fullname ← name & " " & surname
WRITEFILE contacts.txt, fullname
NEXT count
CLOSEFILE contacts.txt
Output on screen all the names of your friends that are recorded in the file contacts.
Solution:
OPENFILE contacts.txt FOR READ
WHILE NOT EOF DO
READFILE contacts.txt, line
OUTPUT line
ENDWHILE
CLOSEFILE contacts.txt