Reading from and writing to text files. The OPEN-USE-CLOSE pattern. Detecting end-of-file with EOF. Why programs use files instead of just memory. Common file-handling errors and how to avoid them.
At a glance
OPENFILE → READ/WRITE → CLOSEFILE — the standard pattern.
WRITE mode overwrites; APPEND mode adds at end.
EOF() detects end of file in read loops.
Files PERSIST after the program ends (unlike RAM).
Three ways to open; each does something different.
Cambridge tests three file-open modes:
READ. Open for reading. The read pointer starts at the beginning. Each READFILE moves the pointer forward by one record/line.
WRITE. Open for writing. EXISTING CONTENT IS OVERWRITTEN — the file is treated as empty. Each WRITEFILE adds a new record/line.
APPEND. Open for writing, but new data is added at the END. Existing content is preserved. Used for log files, transaction journals, audit trails.
Cambridge tip. When writing a question that asks 'add to an existing file without overwriting', the answer is APPEND, not WRITE.
READ — read from existing file.
WRITE — overwrite existing content.
APPEND — add to the end without overwriting.
End-of-file (EOF)
▼
Loop until the file runs out.
When you read a file, you usually don't know in advance how many records it has. The EOF function returns TRUE when the read pointer has reached the end.
OPENFILE "names.txt" FOR READ
WHILE NOT EOF("names.txt")
READFILE "names.txt", Name
OUTPUT Name
ENDWHILE
CLOSEFILE "names.txt"
Why EOF is important. Letting the program 'know when to stop' makes it work for files of ANY size. Hard-coding a count (FOR Counter ← 1 TO 10) breaks as soon as the file changes.
Common mistake. Reading PAST the end of file generates a run-time error in most languages. Always check EOF BEFORE reading.
Cambridge tip. Mark scheme expects WHILE NOT EOF(...) or equivalent. UNTIL EOF (REPEAT loop) is also accepted but has subtly different behaviour for empty files.
1. Persistence. RAM is VOLATILE — when the program ends or the computer is turned off, contents are wiped. Files live on secondary storage (HDD/SSD) and survive. Crucial for:
User data that must be saved between sessions.
Logs that need to be reviewed later.
Configuration that needs to outlive the program.
2. Portability and scale.
Files can be COPIED between machines, programs, users.
Files can hold data sets too large to fit in RAM.
Files become the SHARED FORMAT between programs (CSV between Excel and a Python script, for example).
Trade-offs.
Files are MUCH slower than RAM (HDD ~100,000× slower; SSD ~100× slower).
Programs typically load files into memory for fast access, work in RAM, then write back to disk when done.
Cambridge tip. When asked 'why use a file', the expected answer pairs are: PERSISTENCE (survive program/power off) AND PORTABILITY/SCALE (transfer / large data sets).
Modes: READ, WRITE (overwrite), APPEND (add at end).
EOF() — TRUE at end of file.
Always close — flush buffers + release resources.
Files persist; RAM doesn't.
How it’s examined
File handling appears on every Paper 2. Most-tested questions: write pseudocode to read a file (8 marks), write pseudocode to append data (6 marks), explain WHY files are used (4 marks). Examiner reports flag missing CLOSEFILE and reading past EOF as the two most common errors.
Step-by-step solutions to past-paper-style questions on file handling, written exactly the way a tutor would explain them at the board.
1Why use files? (2 marks)
Getting started• file-handling, purpose
▼
Question
State TWO reasons a program would write data to a file rather than keep it in memory. (2 marks)
Step-by-step solution
Step 1
Persistence (1 mark). Memory (RAM) is volatile — when the program ends or the computer is switched off, its contents are lost. A file is stored on secondary storage, so the data is still there the next time the program runs.
Step 2
Sharing / scale (1 mark). A file can be transferred between programs, users and machines, and can hold a data set too large to fit in RAM. Data held only in memory is private to one running program.
Answer
Files persist on secondary storage, so data survives the program ending / the power being switched off (memory is volatile). 2. Files can be shared/transferred between programs and machines and can store more data than fits in RAM.
Examiner tip
AO1. One mark per distinct reason. Examiners reward 'persistence/non-volatile' and 'sharing/larger than RAM' — repeating the same idea twice scores once.
2Write user data to a file (3 marks)
Getting started• Adapted from 0478/22 Oct/Nov 2024 Q5• file-handling, write
▼
Question
Write pseudocode that reads 10 names from the user and writes them to a file called "Names.txt". (3 marks)
Step-by-step solution
Step 1
Open for write (1 mark).OPENFILE "Names.txt" FOR WRITE — opens the file for writing; any existing content is overwritten.
Step 2
Loop and write (1 mark). A count-controlled FOR loop runs 10 times; inside it, INPUT Name then WRITEFILE "Names.txt", Name writes that record as a new line.
Step 3
Close (1 mark).CLOSEFILE "Names.txt" flushes buffered data and releases the file.
Answer
OPENFILE "Names.txt" FOR WRITE
FOR Counter ← 1 TO 10
INPUT Name
WRITEFILE "Names.txt", Name
NEXT Counter
CLOSEFILE "Names.txt"
Examiner tip
AO3. The mark scheme strictly enforces the OPEN → USE → CLOSE pattern; forgetting CLOSEFILE is the single most common lost mark.
3Read a file until EOF (4 marks)
Building confidence• file-handling, read, eof
▼
Question
Write pseudocode that reads every name from "Names.txt" and outputs each one. The number of names is unknown. (4 marks)
Step-by-step solution
Step 1
Open for read (1 mark).OPENFILE "Names.txt" FOR READ.
Step 2
Condition-controlled loop on EOF (1 mark). Because the count is unknown, use WHILE NOT EOF("Names.txt"). EOF returns TRUE when the read pointer reaches the end of the file, so the loop handles a file of any size.
Step 3
Read and output (1 mark). Inside the loop, READFILE "Names.txt", Name reads the next record into Name, then OUTPUT Name.
Step 4
Close (1 mark).CLOSEFILE "Names.txt" after the loop ends.
Answer
OPENFILE "Names.txt" FOR READ
WHILE NOT EOF("Names.txt")
READFILE "Names.txt", Name
OUTPUT Name
ENDWHILE
CLOSEFILE "Names.txt"
Examiner tip
AO3. Checking EOF BEFORE reading avoids reading past the end of the file. Hard-coding a fixed count here would not be credited because the size is unknown.
4Append a record without losing data (4 marks)
Building confidence• 0478 Paper 2 — style• file-handling, append
▼
Question
A file "Members.txt" already contains a list of member names. Write pseudocode that adds one new member name (entered by the user) to the end of the file without overwriting the existing names. (4 marks)
Step-by-step solution
Step 1
Choose APPEND, not WRITE (1 mark).WRITE mode overwrites everything already in the file. To keep the existing names you must open in APPEND mode, which adds new data at the end.
Step 2
Input the new name (1 mark).INPUT NewMember collects the value to store.
Step 3
Open, write, close (2 marks).OPENFILE "Members.txt" FOR APPEND, then WRITEFILE "Members.txt", NewMember, then CLOSEFILE "Members.txt".
AO3. The discriminating mark is choosing APPEND over WRITE. Opening FOR WRITE here would destroy the existing records and lose the data-preservation mark.
5Count records in a file (5 marks)
Stretch• 0478 Paper 2 — style• file-handling, read, count, eof
▼
Question
Write pseudocode that counts how many lines (records) are stored in "Scores.txt" and outputs the total. (5 marks)
Step-by-step solution
Step 1
Initialise a counter (1 mark).Total ← 0 before opening the file.
Step 2
Open for read (1 mark).OPENFILE "Scores.txt" FOR READ.
Step 3
Loop until EOF, incrementing (2 marks).WHILE NOT EOF("Scores.txt"): read the next record into a variable (this advances the read pointer) and add 1 to Total. The read is essential — without it the loop never reaches EOF.
Step 4
Close and output (1 mark).CLOSEFILE "Scores.txt", then OUTPUT Total.
Answer
Total ← 0
OPENFILE "Scores.txt" FOR READ
WHILE NOT EOF("Scores.txt")
READFILE "Scores.txt", Line
Total ← Total + 1
ENDWHILE
CLOSEFILE "Scores.txt"
OUTPUT Total
Examiner tip
AO3. A frequent error is incrementing without reading inside the loop, which means EOF is never reached and the program loops forever. The READFILE must be inside the loop to advance the pointer.
6Search a file for a matching record (6 marks)
Stretch• 0478 Paper 2 — style• file-handling, read, search, eof
▼
Question
A file "Members.txt" stores one member name per line. Write pseudocode that asks the user for a name and outputs "Found" if that name is in the file, or "Not found" otherwise. (6 marks)
Step-by-step solution
Step 1
Input target and a flag (1 mark).INPUT Target and set a Boolean flag Found ← FALSE to remember whether a match has been seen.
Step 2
Open for read (1 mark).OPENFILE "Members.txt" FOR READ.
Step 3
Linear search loop (2 marks).WHILE NOT EOF("Members.txt"): read the next name, and if it equals Target, set Found ← TRUE. The loop must keep checking EOF so it stops cleanly at the end.
Step 4
Close (1 mark).CLOSEFILE "Members.txt" after the search.
Step 5
Report result (1 mark).IF Found = TRUE THEN OUTPUT "Found" ELSE OUTPUT "Not found".
Answer
INPUT Target
Found ← FALSE
OPENFILE "Members.txt" FOR READ
WHILE NOT EOF("Members.txt")
READFILE "Members.txt", CurrentName
IF CurrentName = Target
THEN
Found ← TRUE
ENDIF
ENDWHILE
CLOSEFILE "Members.txt"
IF Found = TRUE
THEN
OUTPUT "Found"
ELSE
OUTPUT "Not found"
ENDIF
Examiner tip
AO3. Using a Boolean flag is the standard linear-search technique. Outputting inside the loop instead would print a result for every line; the flag lets a single 'Not found' be produced when no record matches.
Model Answers — File Handling
High-scoring sample answers for file handling on the Cambridge IGCSE 0478 paper, with examiner-style notes mapping each response to the mark scheme and assessment objectives.
Question 1
0478 Paper 2 — style2 marks
Write pseudocode to open the file Log.txt for writing, write the single value stored in the variable Entry to it, then close the file. [2]
Model answer
OPENFILE "Log.txt" FOR WRITE
WRITEFILE "Log.txt", Entry
CLOSEFILE "Log.txt"
Why this scores
AO3. 1 mark: OPENFILE ... FOR WRITE plus WRITEFILE of Entry. 1 mark: CLOSEFILE. The CLOSEFILE mark is explicitly separate — omitting it loses half the question.
Question 2
0478 Paper 2 — style4 marks
The file Temps.txt stores one temperature per line. Write pseudocode that reads and outputs every temperature, stopping correctly at the end of the file. The number of temperatures is not known. [4]
Model answer
OPENFILE "Temps.txt" FOR READ
WHILE NOT EOF("Temps.txt")
READFILE "Temps.txt", Temperature
OUTPUT Temperature
ENDWHILE
CLOSEFILE "Temps.txt"
Why this scores
AO3. 1 mark OPENFILE ... FOR READ; 1 mark loop controlled by WHILE NOT EOF(...); 1 mark READFILE into a variable AND OUTPUT it inside the loop; 1 mark CLOSEFILE. The EOF condition is the discriminating mark — a fixed-count loop is not credited because the size is unknown.
Question 3
0478 Paper 2 — style6 marks
The file Members.txt already holds a list of names. Write pseudocode that repeatedly asks the user for a name and appends it to the file (preserving existing names), stopping when the user enters "END". The word "END" must NOT be written to the file. [6]
Model answer
OPENFILE "Members.txt" FOR APPEND
INPUT Name
WHILE Name <> "END"
WRITEFILE "Members.txt", Name
INPUT Name
ENDWHILE
CLOSEFILE "Members.txt"
Why this scores
AO3. 1 mark OPENFILE ... FOR APPEND (NOT WRITE — preserving existing data); 1 mark first INPUT before the loop (priming read); 1 mark loop condition WHILE Name <> "END"; 1 mark WRITEFILE of the name; 1 mark second INPUT inside the loop so "END" is detected and not written; 1 mark CLOSEFILE. The priming-read pattern is what keeps "END" out of the file.
Question 4
0478 Paper 2 — style8 marks
The file Results.txt stores one integer mark per line. Write pseudocode that reads the whole file, counts how many marks are 50 or above (a pass), and outputs the number of passes. [8]
Model answer
DECLARE Mark : INTEGER
DECLARE Passes : INTEGER
Passes ← 0
OPENFILE "Results.txt" FOR READ
WHILE NOT EOF("Results.txt")
READFILE "Results.txt", Mark
IF Mark >= 50
THEN
Passes ← Passes + 1
ENDIF
ENDWHILE
CLOSEFILE "Results.txt"
OUTPUT "Number of passes: ", Passes
Why this scores
AO3. Marks: counter initialised to 0; OPENFILE ... FOR READ; WHILE NOT EOF(...) loop; READFILE into Mark inside the loop; correct threshold test IF Mark >= 50; increment Passes; CLOSEFILE; OUTPUT of the total. The READFILE must sit inside the loop so EOF is eventually reached; the >= 50 boundary (50 counts as a pass) is a precision mark.
Question 5
0478 Paper 2 — style12 marks
The file Scores.txt contains at most 100 integer scores, one per line. Write pseudocode that reads the scores from the file into an array, then finds and outputs the highest score and how many scores were read. [12]
Model answer
DECLARE Scores : ARRAY[1:100] OF INTEGER
DECLARE Count : INTEGER
DECLARE Index : INTEGER
DECLARE Highest : INTEGER
Count ← 0
// Read the file into the array
OPENFILE "Scores.txt" FOR READ
WHILE NOT EOF("Scores.txt")
READFILE "Scores.txt", NextScore
Count ← Count + 1
Scores[Count] ← NextScore
ENDWHILE
CLOSEFILE "Scores.txt"
// Find the highest score in the array
IF Count > 0
THEN
Highest ← Scores[1]
FOR Index ← 2 TO Count
IF Scores[Index] > Highest
THEN
Highest ← Scores[Index]
ENDIF
NEXT Index
OUTPUT "Highest score: ", Highest
OUTPUT "Scores read: ", Count
ELSE
OUTPUT "No scores in file"
ENDIF
Why this scores
AO3 (with AO2). Marks across two phases. Read phase: array + Count declared/initialised; OPENFILE ... FOR READ; WHILE NOT EOF(...); READFILE inside loop; increment Count and store into Scores[Count]; CLOSEFILE. Process phase: initialise Highest to the first element; FOR loop from 2 to Count; comparison IF Scores[Index] > Highest updating Highest; output highest and Count. The empty-file guard (IF Count > 0) is a robustness mark. Indexing the file directly (treating lines as array elements) would lose marks — the file must be read sequentially into the array first.
Question 6
0478 Paper 2 — 15-mark scenario style15 marks
Unseen scenario. A sports club stores its members in a file Members.txt. Each line holds a member name and an integer age separated by a comma, for example Asha,17.
Write pseudocode that:
reads every record from Members.txt,
writes the names of all members aged 18 or over to a new file Adults.txt,
counts how many adult members were found,
and outputs the count.
Use the file-handling commands OPENFILE, READFILE, WRITEFILE, EOF and CLOSEFILE. You may assume a function SPLIT(line, ",", 1) returns the part before the comma (the name) and SPLIT(line, ",", 2) returns the part after (the age as a string), and a function STRING_TO_NUM(value) converts a string to an integer. [15]
Model answer
DECLARE Line : STRING
DECLARE Name : STRING
DECLARE Age : INTEGER
DECLARE AdultCount : INTEGER
AdultCount ← 0
// Open the source file for reading and the destination file for writing
OPENFILE "Members.txt" FOR READ
OPENFILE "Adults.txt" FOR WRITE
// Process every record until end of file
WHILE NOT EOF("Members.txt")
READFILE "Members.txt", Line
Name ← SPLIT(Line, ",", 1)
Age ← STRING_TO_NUM(SPLIT(Line, ",", 2))
IF Age >= 18
THEN
WRITEFILE "Adults.txt", Name
AdultCount ← AdultCount + 1
ENDIF
ENDWHILE
// Close both files
CLOSEFILE "Members.txt"
CLOSEFILE "Adults.txt"
OUTPUT "Number of adult members: ", AdultCount
Why this scores
AO3 (drawing on AO1/AO2) — the final 15-mark unseen scenario. Mark map: declarations/initialise AdultCount ← 0; OPENFILE "Members.txt" FOR READ; OPENFILE "Adults.txt" FOR WRITE; WHILE NOT EOF("Members.txt") loop; READFILE into Line inside the loop; split out the name; split out and convert the age to an integer; age test IF Age >= 18 (18 counts as adult — boundary mark); WRITEFILE "Adults.txt", Name for qualifying members; increment AdultCount; CLOSEFILE "Members.txt"; CLOSEFILE "Adults.txt" (both closes are separately credited); OUTPUT the count. Reading until EOF and closing BOTH files are explicit marks examiners look for; writing the whole line instead of just the name, or opening Adults.txt FOR APPEND/READ, would lose marks.
Key Definitions and Keywords — File Handling
Definitions to memorise and the exact keywords mark schemes credit for file handling answers — sharpened from recent examiner reports for the 2026 0478 sitting.
File
Examiner keyword▼
A named collection of related data stored on secondary storage. Persists beyond the program's lifetime.
Text file
▼
A file that stores data as readable characters, typically organised into lines.
OPENFILE
Examiner keyword▼
Cambridge pseudocode command to open a file in a specified mode (READ, WRITE, APPEND).
READFILE
Examiner keyword▼
Cambridge pseudocode command to read the next line / record from an open file into a variable.
WRITEFILE
Examiner keyword▼
Cambridge pseudocode command to write a value to an open file. Adds a new line / record.
CLOSEFILE
Examiner keyword▼
Cambridge pseudocode command to close an open file. Flushes any buffered data and releases the file resource.
EOF (End-of-File)
Examiner keyword▼
A condition / function that becomes TRUE when the read pointer reaches the end of a file. Used to terminate read loops on files of unknown length.
WRITE mode
▼
Opens a file for writing. Existing content is OVERWRITTEN.
APPEND mode
▼
Opens a file for writing such that new data is added AT THE END, preserving existing content.
Common Mistakes and Misconceptions — File Handling
The traps other students keep falling into on file handling questions — taken from recent Cambridge IGCSE 0478 examiner reports and mark schemes — and how to avoid them.
✕Forgetting CLOSEFILE
0478 Examiner Reports 2022-2024
▼
Why it happens
The program seems to work without it.
How to avoid it
Without CLOSEFILE, buffered writes may be lost and the file resource is held longer than necessary. Mark scheme penalises this every time.
✕Using WRITE when APPEND was needed
▼
Why it happens
Students don't notice the difference.
How to avoid it
WRITE overwrites existing content; APPEND adds to the end. Use APPEND when keeping existing records.
✕Reading past the end of file
▼
Why it happens
Students hard-code the read count.
How to avoid it
If the file size isn't known, loop with WHILE NOT EOF(...). Hard-coding a count fails when the file changes.
✕Treating file lines as array elements you can index
▼
Why it happens
Conceptual confusion.
How to avoid it
Files are sequential — you read one line at a time. To use index access, read the whole file into an array first, then index that.
File Handling — frequently asked questions
The things students keep getting wrong in this sub-topic, answered.