File Handling · Cambridge syllabus 8.3 · Lesson 2 of 2
Reading and Writing Files
Open a file in the mode needed, READ or WRITE, read or write a line or a single item at a time, then close it. Each READFILE reads the next line. Opening a file FOR WRITE creates a new file, and anything already in the file is lost.
By the end, you can
- Open a file for reading.
- Read individual data items.
- Read lines of text.
- Open a file for writing.
- Write individual data items.
- Write lines of text.
- Close files correctly.
File operations
File handling has three stages in a fixed order: open the file and say what you intend to do with it, read or write, then close it.
OPENFILE "Scores.txt" FOR READ prepares it for reading; the file name is a string, so it is written in quotes. READFILE "Scores.txt", Score reads the next item or line into the variable Score, and each READFILE reads the following one. To read a file of five lines, put the READFILE inside FOR Count ← 1 TO 5 and NEXT Count.
OPENFILE "Results.txt" FOR WRITE prepares a file for writing, and this is the one that bites: opening for write creates a new file, and any data already in a file of that name is lost. WRITEFILE "Results.txt", Score writes one item or line from the variable. The 0478 file modes are only READ and WRITE, and a file is open in one mode at a time.
CLOSEFILE "Scores.txt" finishes. Every file that was opened should be closed when it is no longer needed: a program that ends without closing can lose the last data it wrote, and a file must be closed before it is opened again in the other mode.
Copying a line from one file to another uses all of these: DECLARE LineOfText : STRING, OPENFILE "FileA.txt" FOR READ, OPENFILE "FileB.txt" FOR WRITE, READFILE "FileA.txt", LineOfText, WRITEFILE "FileB.txt", LineOfText, then CLOSEFILE for each file.
Worth remembering
- Open, then read or write, then close — always in that order.
- File names are strings in quotes; the modes are READ and WRITE.
- Opening FOR WRITE creates a new file, and any data already in it is lost.
- Each READFILE or WRITEFILE handles one item or line; use a loop for several.
Worked example
OPENFILE "Scores.txt" FOR READ, then FOR Count ← 1 TO 3 with READFILE "Scores.txt", Score inside it, then CLOSEFILE "Scores.txt".
Practice
Warm-up · not marked
Check your understanding
Answer in your own words, then compare with the worked answer. Nothing here is saved or scored.
Worked answer
Five: each READFILE reads the next line, so a FOR loop from 1 to 5 can read them.
Check your method, units and explanation against it.
Marked practice
Set 1 of 4 · easiest first · Checked as you go, with the worked answer. Sign in or create a free account to save your progress.