IGCSE · Practice questions · Reading from and writing to files

Open, use, close.

Six original Cambridge-style questions on file handling in 0478 pseudocode, with mark points.

Original questions All questions on this page are original work, written in the Cambridge IGCSE style. They are not from past papers. They test the same concepts and skills the syllabus rewards.
Keep these straight

Open, use, close.

01
Explain
[2 marks]

Explain why a program might store data in a file.

  • Data held in variables is lost when the program stops running. ✓
  • Data in a file is stored permanently, so it can be accessed again later (by this or another program). ✓
02
Write
[3 marks]

Write pseudocode to input a user's name and store it in a new file called User.txt.

  • INPUT UserName ✓
  • OPENFILE "User.txt" FOR WRITE then WRITEFILE "User.txt", UserName ✓
  • CLOSEFILE "User.txt" ✓
03
Write
[4 marks]

The file Words.txt contains at least five lines of text. Write pseudocode to read the first five lines and output each one.

  • OPENFILE "Words.txt" FOR READ ✓
  • FOR Count ← 1 TO 5 ... NEXT Count ✓
  • READFILE "Words.txt", LineOfText then OUTPUT LineOfText inside the loop ✓
  • CLOSEFILE "Words.txt" after the loop ✓
04
Trace
[3 marks]

Data.txt contains the lines 7, 4 and 9. State the output.

DECLARE Value : INTEGER
DECLARE Total : INTEGER
Total ← 0
OPENFILE "Data.txt" FOR READ
READFILE "Data.txt", Value
Total ← Total + Value
READFILE "Data.txt", Value
Total ← Total + Value
CLOSEFILE "Data.txt"
OUTPUT Total, " ", Value
  • The first READFILE reads 7: Total = 7. ✓
  • The second READFILE reads the next line, 4: Total = 11. ✓
  • Output: 11 4 (the third line, 9, is never read) ✓
05
Explain
[2 marks]

A program opens Results.txt FOR WRITE every time it runs, to add one new result. Explain the problem.

  • WRITE mode creates a new file each time the program runs. ✓
  • So the previous results are lost and the file only ever holds the latest result. ✓
06
Write
[4 marks]

Write pseudocode to copy the first line of Old.txt into a new file New.txt.

  • OPENFILE "Old.txt" FOR READ and OPENFILE "New.txt" FOR WRITE ✓
  • READFILE "Old.txt", LineOfText ✓
  • WRITEFILE "New.txt", LineOfText ✓
  • CLOSEFILE "Old.txt" and CLOSEFILE "New.txt" ✓

Mark this once you have attempted all six and checked your working. It records a Practiced badge on the topic and adds a one-time bonus. Revealing the solutions alone does not count.