Programming
File handling
Why programs store data in files, and how to open, write, read, and close a text file in pseudocode.
Examples use Cambridge pseudocode for the 2026–2028 syllabus.
Why use files?
Variables live in RAM, so their values disappear when the program ends. Storing data in a file keeps it permanently, so it can be loaded the next time the program runs, or used by another program.
Open, use, close
Every file operation follows the same pattern:
- 1Open
OPENFILE "scores.txt" FOR WRITEorFOR READ - 2Write or read
WRITEFILEsends a line to the file;READFILEreads the next line into a variable. - 3Close
CLOSEFILEsaves the file and frees it for other programs.
Watch out. Opening a file FOR WRITE replaces anything already in it.
Writing to a file
DECLARE Name : STRING
OPENFILE "names.txt" FOR WRITE
INPUT Name
WRITEFILE "names.txt", Name
CLOSEFILE "names.txt"Reading from a file
Each READFILE reads the next line of the file into a variable.
DECLARE FirstLine : STRING
OPENFILE "names.txt" FOR READ
READFILE "names.txt", FirstLine
OUTPUT "The first name is ", FirstLine
CLOSEFILE "names.txt"Check yourself
Why might a game save high scores to a file instead of a variable?Show answer
Variables are lost when the program closes; a file keeps the scores permanently for next time.
What must happen before a program can read a file?Show answer
The file must be opened with OPENFILE ... FOR READ.
References used to build these lessons
We used these official documents as references when building this course's lessons. They are the sources for the syllabus structure and course requirements.
Cambridge International · 2210 · Exams 2026–2028