File Handling
Saving data so it still exists after the program closes.
WATCH IT EXPLAINED
EXPLORE IT IN 3D
The file archive
A cabinet of text files, a desk that reads and writes them, and a terminal to run the programs. Open, write, read and close real files — then watch them break the classic ways.
Why programs save data in files
Variables are lost when a program stops; a file keeps data until the next run.
| Variables and arrays | A file | |
|---|---|---|
| Held in | RAM (main memory), while the program runs | secondary storage, such as a hard disk |
| When the program stops | they are lost | the data is still there next time |
Any data that must last longer than one run belongs in a file. For example:
- a high score in a game;
- a class register;
- saved settings.
Example:In the figure, press Run the program again, and the file remembers the best score. With a variable only, the best score starts again on every run.
Open, use, close
Every file job has three steps: open the file, read or write, then close it.
- Open:
OPENFILEopens the file and states its file mode. UseFOR READto read data from it, orFOR WRITEto write data to it. - Use: each
READFILEorWRITEFILEreads or writes one item. - Close:
CLOSEFILEcloses the file when the program has finished with it.
- The file's name is a string, so it goes in quotes.
- A file is open in only one mode at a time. You cannot write to a file you opened FOR READ.
- Close every file you open.
Exam:Opening, using and closing the file each earn a separate mark.
OPENFILE <File identifier> FOR <File mode> READFILE <File identifier>, <Variable> WRITEFILE <File identifier>, <Variable> CLOSEFILE <File identifier>
WRITE starts a new file
Opening a file FOR WRITE wipes it and starts again; it never adds to the end.
Opening a file FOR WRITE creates a new, empty file. If a file with that name already exists, everything in it is lost before anything new is written.
Watch out:Opening it FOR WRITE a second time does not add to the end. It starts again.
The IGCSE guide has no mode that adds to a file. To keep the old data:
- Read the old data first.
- Open the file FOR WRITE.
- Write the old and the new data back together.
AS Level adds an APPEND mode for this, but you do not need it at IGCSE.
Reading one item at a time
READFILE reads one line at a time, from the top, so read in the same order you wrote.
READFILE reads the next line of the file into a variable. The next READFILE reads the line after it. So the file is read from the top, one line at a time.
A line can hold a single item of data, such as a name or a number. Or it can hold a whole line of text.
Watch out:The file has no labels, only lines. Read the items in the same order they were written, into variables declared with the right data types.
Swap two READFILE lines in the figure, and the age and the score change places.
Saving an array and loading it back
Save an array with a loop that writes one element per line; load it with the same loop reading.
| Job | Open the file | Loop |
|---|---|---|
| Save | FOR WRITE | write one element to each line |
| Load | FOR READ | loop the same number of times, reading one line into each element |
The array's bounds tell you how many elements there are. So a count-controlled FOR loop is right for both jobs.
The code below is the saving loop. In the figure, the array is saved, set back to 0, and then filled again from the file.
OPENFILE "Temps.txt" FOR WRITE FOR Day ← 1 TO 7 WRITEFILE "Temps.txt", Temps[Day] NEXT Day CLOSEFILE "Temps.txt"
Knowing how much to read
A program must know how many lines to read, so it never reads past the end of the file.
A program must not read past the last line of a file. So it needs to know how many lines to read. There are two ways:
- An exam question may tell you how many items there are.
- The file can store the count on its first line. Read that number first, then read that many items with a FOR loop.
| The count is | What goes wrong |
|---|---|
| too small | the last names are never read |
| too big | the program tries to read past the end |
Watch out:WHILE NOT EOF(…) in a book is the AS Level way. EOF is not in the IGCSE guide.
DECLARE HowMany : INTEGER DECLARE Line : INTEGER DECLARE Name : STRING OPENFILE "Club.txt" FOR READ READFILE "Club.txt", HowMany FOR Line ← 1 TO HowMany READFILE "Club.txt", Name OUTPUT Name NEXT Line CLOSEFILE "Club.txt"
File handling in the exam
File questions are marked point by point: open, read or write, close, and sometimes declare.
You get marks for each of these:
- opening the file with the name the question gives, in the right mode;
- writing (or reading) the right variable;
- closing the file;
- in some questions, declaring the variables.
Exam:Write the file name in quotes every time. The guide says the name is a string. The mark schemes print it both with and without quotes, so quotes are the safe choice.
The code below writes a score to a file, then reads it back.
DECLARE Score : INTEGER Score ← 78 // writing: open, write, close OPENFILE "Scores.txt" FOR WRITE WRITEFILE "Scores.txt", Score CLOSEFILE "Scores.txt" // reading: open, read, close OPENFILE "Scores.txt" FOR READ READFILE "Scores.txt", Score CLOSEFILE "Scores.txt" OUTPUT Score
RUN THE PSEUDOCODE
Write the pseudocode your syllabus uses and press Run. Assignment is the arrow — type <- and it works the same as ←. Both syllabuses are accepted, so OUTPUT and PRINT both work; where a word differs from the one the exam prints, the runner says so.
Press Run to see what it doesTotal ← 0
FOR Count ← 1 TO N
Total ← Total + Count
NEXT Count
OUTPUT TotalSTARTN = 5
| Count | Total | OUTPUT |
|---|---|---|
One row per pass through the loop. Leave a cell blank if it does not change on that pass.
KEY TERMS
CHECK YOURSELF
1.What happens to a file's contents when it is opened FOR WRITE?
2.A program has written its last line with WRITEFILE. Which line must come next?
3.Why store data in a file rather than only in variables?
4.Player.txt holds three lines: Saruul, 14 and 2350. A program reads them into Name, then Score, then Age. What does Age hold?
5.The first line of Club.txt is 3, and four names follow it. The program reads the count, then reads that many names with a FOR loop. What happens?