Teachers' Portal  /  IGCSE Computer Science 0478  /  Programming  /  Reading from and writing to files
Lesson pack · IGCSE Computer Science 0478 · 8.3 · IGCSE

Reading from and writing to files

Data that stays. When a program stops, every variable it used is lost.

Student lesson Lab, full screen
At a glance

The shape of the lesson

Topic
Programming
Syllabus reference
Cambridge IGCSE Computer Science 0478, 8.3
Level
IGCSE
Duration
45 minutes, lab-led; stretches to a 60 minute block (see the contingency notes)
Position in topic
Lesson 11 of 11 in Programming; follows Two-dimensional arrays and nested loops
Central model
Fig. 1: WRITEFILE copies data from a variable into the file; READFILE copies it back
Cooperative structure
Assessment
Stage 1 check and the exam-style plenary from the student lesson, plus the worksheet as the exit task
Learning objectives

By the end of the lesson, learners can

Section by section
  • Why use files?: In the lab, choose Write a file, then read it.
  • Writing to a file: Open the file in WRITE mode, write each item with WRITEFILE, then close it.
  • Reading from a file: Open the file in READ mode.
Key points to leave on the board
  • Purpose: data in a file is kept after the program ends and can be used again.
  • Open: OPENFILE "name" FOR READ or FOR WRITE; one mode at a time.
  • Use: READFILE "name", Variable reads the next line; WRITEFILE "name", Value writes one.
  • Close: CLOSEFILE "name". WRITE mode replaces any existing contents.
The core visual model

One picture every idea returns to

Variables are held in main memory and are lost when the program ends. Storing data in a file keeps it permanently in secondary storage, so it can be used again later, by this or another program. In pseudocode: OPENFILE "Names.txt" FOR READ or FOR WRITE, then READFILE to read the next line into a variable, WRITEFILE to write a value, and CLOSEFILE when finished. Opening a file FOR WRITE creates a new file: any existing data in it is lost.

program (in RAM) NameCount lost when theprogram stops Names.txt (storage) AliBeaChen WRITEFILE READFILE data in a file is kept after the program ends
Fig. 1: WRITEFILE copies data from a variable into the file; READFILE copies it back
Lesson sequence

Forty-five minutes, phase by phase

TimePhaseWhat happens in the roomGrouping
0 to 5 minHook: predictOpen with the question in the title, Data that stays.. When a program stops, every variable it used is lost. Put the figure on the board: it is the one picture every idea in the lesson returns to.Whole class, then pairs
5 to 13 minTeach and check: Why use files?In the lab, choose Write a file, then read it. Project tab 6 of the lab (Text files) and let a student drive it while the class predicts.Whole class, then pairs
13 to 21 minTeach and check: Writing to a fileOpen the file in WRITE mode, write each item with WRITEFILE, then close it. Model the worked example Running it twice on the board, one line at a time.Pairs
21 to 30 minTeach and check: Reading from a fileOpen the file in READ mode. Model the worked example Dry run on the board, one line at a time. Your turn: The program is run again and the player scores 200. What does the file contain afterwards?Jigsaw
30 to 36 minCheckThe four Stage 1 questions from the student lesson, answered on mini whiteboards or by show of fingers. Re-teach the one most get wrong.Individual, then whole class
36 to 43 minPlenaryThe exam-style questions from Stage 2, one at a time: thirty seconds alone, then a random call. The feedback lines in the key give the examiner's wording.Individual, random call
43 to 45 minExit and homeworkSet the worksheet below (6 questions, 18 marks). Learners self-assess against the objectives before they leave.Individual
Timing and contingency

Protect the parts that carry the learning

The sequence carries about fifty minutes of material, so the lab is driven by one student while the class predicts rather than explored freely. Times are a guide.

Protected: the check at 30 minutes. It is the only individual read on whether the key idea landed, and it is not cut.

Cut first if the build overruns: the last check in Reading from a file, never the check or the plenary.

In a 60 minute block: run worksheet questions 1 to 3 in class as a Rally Coach set and model both the hardest worked example and its check live.

Running the cooperative task

Jigsaw

Split the content into expert pieces. Expert groups master one piece each, then regroup so every home team has one expert per piece, and each expert teaches their piece to the team.

The full structure, with its variations and the other twelve, is on the cooperative-learning page.

Examiner traps to pre-empt

What to head off, and how

Trap learners fall intoTeaching move that pre-empts it
"Files save data" earns little.Say that data in variables is lost when the program ends, but data in a file is stored permanently so it can be accessed again later.
Opening an existing file in WRITE mode wipes it.Only one mode is used at a time, so to read and then rewrite a file, close it and open it again in the other mode.
Always CLOSEFILE when you have finished with a file.Closing it makes sure the data is saved and lets the file be opened again, for example in the other mode.
Worksheet

Reading from and writing to files: worksheet

6 questions, 18 marks. Written in the style of the papers; no past paper question is reproduced.

NameClassDate
Q1 · explain[2 marks]

Explain why a program might store data in a file.

Q2 · write[3 marks]

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

Q3 · 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.

Q4 · 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
Q5 · explain[2 marks]

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

Q6 · write[4 marks]

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

Answer key and marking notes
Q1 · 2 marks
  • 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).
Q2 · 3 marks
  • INPUT UserName
  • OPENFILE "User.txt" FOR WRITE then WRITEFILE "User.txt", UserName
  • CLOSEFILE "User.txt"
Q3 · 4 marks
  • 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
Q4 · 3 marks
  • 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)
Q5 · 2 marks
  • 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.
Q6 · 4 marks
  • 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"
Quiz

6 multiple-choice questions on this lesson

From the topic question bank. Assign them in the app for a marked score in your gradebook, or run the topic as a class game.

Q11 mark

Why does a game store its high score in a file rather than only in a variable?

  • AData in a variable is lost when the program ends, but a file keeps it so it can be used next time
  • BA file can be read and written much faster than a variable in main memory
  • CA variable can only hold text, so numbers have to be kept in a file
  • DStoring data in a file stops the program from needing any variables
Q21 mark

A file called Scores.txt already holds data. What happens when it is opened with OPENFILE "Scores.txt" FOR WRITE?

  • AThe existing data is lost and new data written replaces it
  • BNew data written is added after the existing data
  • CThe file can be read but not changed
  • DAn error occurs because the file already exists
Q31 mark

Why will this program not work as intended?

DECLARE Score : INTEGER
OPENFILE "Scores.txt" FOR WRITE
READFILE "Scores.txt", Score
OUTPUT Score
CLOSEFILE "Scores.txt"

  • AThe file is opened FOR WRITE, but the program tries to read from it
  • BCLOSEFILE must come before the OUTPUT statement
  • CREADFILE cannot store a value in an INTEGER variable
  • DA file can only be read inside a loop
Q41 mark

This program is run once with the inputs Ann, Ben, Cal and then run again with the inputs Dee, Eve, Fay. What does Names.txt hold after the second run?

DECLARE Name : STRING
DECLARE Count : INTEGER
OPENFILE "Names.txt" FOR WRITE
FOR Count ← 1 TO 3
    INPUT Name
    WRITEFILE "Names.txt", Name
NEXT Count
CLOSEFILE "Names.txt"

  • ADee, Eve, Fay
  • BAnn, Ben, Cal, Dee, Eve, Fay
  • CFay only
  • DAnn, Ben, Cal
Q51 mark

HighScore.txt holds 120. The program is run twice: first with the input 150, then with the input 130. What does the file hold after the second run, and what does the second run output?

DECLARE HighScore : INTEGER
DECLARE Score : INTEGER
OPENFILE "HighScore.txt" FOR READ
READFILE "HighScore.txt", HighScore
CLOSEFILE "HighScore.txt"
INPUT Score
IF Score > HighScore
  THEN
    OPENFILE "HighScore.txt" FOR WRITE
    WRITEFILE "HighScore.txt", Score
    CLOSEFILE "HighScore.txt"
    OUTPUT "New high score!"
ENDIF

  • A150; the second run outputs nothing
  • B130; the second run outputs New high score!
  • C120; the second run outputs New high score!
  • D150; the second run outputs New high score!
Q61 mark

FileA.txt holds three lines of text. What does FileB.txt hold after this program runs?

DECLARE LineOfText : STRING
OPENFILE "FileA.txt" FOR READ
OPENFILE "FileB.txt" FOR WRITE
READFILE "FileA.txt", LineOfText
WRITEFILE "FileB.txt", LineOfText
CLOSEFILE "FileA.txt"
CLOSEFILE "FileB.txt"

  • AOnly the first line of FileA.txt
  • BAll three lines of FileA.txt
  • COnly the last line of FileA.txt
  • DNothing, because FileA.txt is closed before FileB.txt
Quiz key
Q1: A

Variables are held in main memory and disappear when the program ends; a file is kept in secondary storage, so the high score can be read again the next time the program runs. Files are slower to access than variables, not faster. Variables can hold any data type. Data read from a file is still placed in variables to be used.

Q2: A

Opening a file FOR WRITE creates a new, empty file, so anything already in it is lost. Adding to the end of existing data is not what WRITE mode does. Reading needs FOR READ. No error occurs: the old file is simply replaced.

Q3: A

READFILE needs the file to be opened FOR READ; opening it FOR WRITE also wipes the data that was meant to be read. Score is already in a variable, so it can be output before or after closing the file. A value read from a file can be stored in a variable of a suitable type. A single line can be read without a loop.

Q4: A

The second run opens Names.txt FOR WRITE, which wipes Ann, Ben and Cal; the loop then writes Dee, Eve and Fay, one per line. Keeping all six would need the data to be added rather than replaced. Each WRITEFILE writes a new line while the file stays open, so Fay is not the only name. Ann, Ben, Cal is the content after the first run only.

Q5: A

Run 1 reads 120; 150 > 120, so 150 is written and New high score! is output. Run 2 reads 150; 130 > 150 is FALSE, so nothing is written or output and the file still holds 150. 130 assumes the second run compares with the original 120. 120 forgets that the first run rewrote the file. The last option has the right file but outputs a message that only appears when the IF is TRUE.

Q6: A

Each READFILE reads the next single line, and there is only one READFILE and one WRITEFILE, so just the first line is copied. Copying all three lines would need the read and write inside a loop that runs three times. The first READFILE always starts at the first line. The order in which the two files are closed does not matter: the line was already written.

Lab and demo

What to project

The student lesson embeds these tabs. Open them full screen on the projector; every slider has a drag handle on the stage.

Slides

Slides for this lesson

A projectable deck for every pack is on the way. Until then, present the student lesson full screen: its sections, figure and lab tabs follow the same order as the plan above.

Also for this topic

Everything else you can use

Original work by the TheLucidSTEM team. The worksheet items are written in the style of the papers; no past paper question is reproduced.
Previous lessonTwo-dimensional arrays and nested loops