The shape of the lesson
By the end of the lesson, learners can
- Why files?: Any data that must outlive a single run of a program has to be saved somewhere other than main memory.
- Reading a file: In the lab, run the program that writes three names to a file and then reads one back.
- Writing and appending: WRITE starts a brand-new file every time it is opened; APPEND keeps what is there and adds to the end.
- Why: variables are lost when the program ends; a file stores data permanently for later use.
- Modes: READ, WRITE (new file, old data lost), APPEND (add to the end).
- Read loop:
WHILE NOT EOF(file),READFILE file, StringVar, process,ENDWHILE. - Finish: CLOSEFILE every file you opened, after the loop.
One picture every idea returns to
Data in variables is held in RAM and is lost when the program ends. A file is stored on secondary storage, so the data persists and can be used the next time the program runs or by another program. A text file is a sequence of lines, each read or written as a string, in order. A file is opened in one mode: READ, WRITE (creates a new file; any existing data is lost) or APPEND (adds after the existing data). Use READFILE, WRITEFILE, the EOF function and CLOSEFILE.
Forty-five minutes, phase by phase
| Time | Phase | What happens in the room | Grouping |
|---|---|---|---|
| 0 to 5 min | Hook: predict | Open with the question in the title, Data that stays.. Variables and arrays live in main memory and vanish when the program stops. 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 min | Teach and check: Why files? | Any data that must outlive a single run of a program has to be saved somewhere other than main memory. | Whole class, then pairs |
| 13 to 21 min | Teach and check: Reading a file | In the lab, run the program that writes three names to a file and then reads one back. Project tab 6 of the lab (Writing and reading text files) and let a student drive it while the class predicts. Model the worked example Trace the read loop on the board, one line at a time. Your turn: Why is a WHILE loop used here rather than a REPEAT... UNTIL EOF("Names.txt") loop? | Pairs |
| 21 to 30 min | Teach and check: Writing and appending | WRITE starts a brand-new file every time it is opened; APPEND keeps what is there and adds to the end. Model the worked example Copy without blank lines on the board, one line at a time. Your turn: A program records a new temperature in Temps.txt every hour, but the file only ever holds one reading. Suggest the cause and the fix. | Connect-Extend-Challenge |
| 30 to 36 min | Check | The 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 min | Plenary | The 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 min | Exit and homework | Set the worksheet below (6 questions, 23 marks). Learners self-assess against the objectives before they leave. | Individual |
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 Writing and appending, 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.
Connect-Extend-Challenge
After the new idea, each student writes three lines: how it connects to what they knew, how it extends their thinking, and what still challenges them. Pairs compare, then the challenges become the plenary.
The full structure, with its variations and the other twelve, is on the cooperative-learning page.
What to head off, and how
| Trap learners fall into | Teaching move that pre-empts it |
|---|---|
| "Files are needed to store data" is too vague. | Say that variables are lost when the program ends, so the data must be stored permanently in a file to be used again later. |
| READFILE reads one line into a STRING variable. | If a line holds a number, it is still text until it is converted, so do not declare the READFILE variable as INTEGER. |
| Always CLOSEFILE when you have finished. | An examiner checks that every OPENFILE has a matching CLOSEFILE, with the same file name, after the loop rather than inside it. |
Text files: worksheet
6 questions, 23 marks. Written in the style of the papers; no past paper question is reproduced.
Explain why a program that keeps a list of high scores needs to store them in a file.
Describe the effect of opening a text file in each of these modes: READ, WRITE, APPEND.
Stock.txt contains five lines: Pen, Ink, (blank line), Pad, Pin. State the output of this pseudocode.
Count ← 0
OPENFILE "Stock.txt" FOR READ
WHILE NOT EOF("Stock.txt")
READFILE "Stock.txt", Item
IF Item <> "" THEN
IF MID(Item, 1, 1) = "P" THEN
OUTPUT Item
ENDIF
ELSE
Count ← Count + 1
ENDIF
ENDWHILE
CLOSEFILE "Stock.txt"
OUTPUT CountNames : ARRAY[1:30] OF STRING is a global array; unused elements hold the empty string. Write pseudocode for a procedure SaveNames() that writes every non-empty name to a new file Names.txt, one per line.
Words.txt contains an unknown number of lines. Write pseudocode to read the lines into Words : ARRAY[1:100] OF STRING, stopping at the end of the file or when the array is full, and then output how many lines were stored.
A program adds one line to Visitors.txt each time a visitor signs in. It uses OPENFILE "Visitors.txt" FOR WRITE. At the end of the day the file holds only one name. Explain why and describe how to correct the program.
Answer key and marking notes
- Variables and arrays are held in RAM and are lost when the program ends.
- A file is held on secondary storage, so the scores are still available the next time the program runs.
- READ: data can be read from the file, starting at the first line.
- WRITE: a new file is created for writing; any existing data in the file is lost.
- APPEND: data is written after the existing data in the file.
- Pen is output (starts with P).
- Ink is not output; the blank line adds 1 to Count.
- Pad and Pin are output.
- Final output 1 (the number of blank lines).
PROCEDURE SaveNames()...ENDPROCEDURE.OPENFILE "Names.txt" FOR WRITEbefore the loop.FOR Index ← 1 TO 30...NEXT Index.IF Names[Index] <> "" THEN WRITEFILE "Names.txt", Names[Index].CLOSEFILE "Names.txt"after the loop.
- Declare a counter
Count ← 0and a STRING variable for the line. OPENFILE "Words.txt" FOR READ.WHILE NOT EOF("Words.txt") AND Count < 100.READFILE "Words.txt", LineIn, thenCount ← Count + 1.Words[Count] ← LineIninside the loop, after the increment.CLOSEFILE "Words.txt"andOUTPUT Countafter the loop.
- Opening in WRITE mode creates a new file each time.
- So every earlier name is lost and only the last visitor remains.
- Open the file FOR APPEND, so each name is added after the existing lines (and close it after writing).
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.
Why does a program that keeps a league table between runs need to store it in a file?
- AVariables are held in RAM and are lost when the program ends, but a file on secondary storage persists
- BA file can be read faster than a variable held in main memory
- CArrays cannot hold more than one value unless they are saved to a file
- DA program cannot output data unless it has first been written to a file
Scores.txt already holds 50 lines. A program executes OPENFILE "Scores.txt" FOR WRITE. What happens to the 50 lines?
- AThey are lost, because WRITE creates a new file
- BThey are kept, and new lines are written after them
- CThey are kept, and new lines are written before them
- DThey are kept, and each new line overwrites one old line in turn
Trees.txt holds six lines: Oak, Birch, Ash, Maple, Elm, Cedar. What is output?
Result ← ""
OPENFILE "Trees.txt" FOR READ
WHILE NOT EOF("Trees.txt")
READFILE "Trees.txt", Line
IF LENGTH(Line) > 3 THEN
Result ← Result & RIGHT(Line, 1)
ENDIF
ENDWHILE
CLOSEFILE "Trees.txt"
OUTPUT Result- A
her - B
khhemr - C
BMC - D
BirchMapleCedar
Which sequence adds the line Done to the end of the existing file Log.txt, keeping its current contents?
- A
OPENFILE "Log.txt" FOR APPEND,WRITEFILE "Log.txt", "Done",CLOSEFILE "Log.txt" - B
OPENFILE "Log.txt" FOR WRITE,WRITEFILE "Log.txt", "Done",CLOSEFILE "Log.txt" - C
OPENFILE "Log.txt" FOR READ,WRITEFILE "Log.txt", "Done",CLOSEFILE "Log.txt" - D
OPENFILE "Log.txt" FOR APPEND,READFILE "Log.txt", "Done",CLOSEFILE "Log.txt"
A programmer reads a file with REPEAT READFILE "Data.txt", LineIn ... UNTIL EOF("Data.txt") instead of a WHILE loop. In which situation does this fail?
- AWhen the file is empty, because a READFILE is attempted before EOF is tested
- BWhen the file holds exactly one line, because that line is never read
- CWhen the file holds many lines, because only the last line is read
- DWhen the last line is blank, because EOF becomes TRUE one line early
Out.txt does not exist before this pseudocode runs. What does Out.txt contain at the end?
OPENFILE "Out.txt" FOR WRITE WRITEFILE "Out.txt", "A" CLOSEFILE "Out.txt" OPENFILE "Out.txt" FOR APPEND WRITEFILE "Out.txt", "B" CLOSEFILE "Out.txt" OPENFILE "Out.txt" FOR WRITE WRITEFILE "Out.txt", "C" CLOSEFILE "Out.txt" OPENFILE "Out.txt" FOR APPEND WRITEFILE "Out.txt", "D" CLOSEFILE "Out.txt"
- ATwo lines: C, D
- BFour lines: A, B, C, D
- COne line: D
- DTwo lines: A, B
Quiz key
RAM is volatile and a program's variables are discarded when it ends, so data needed next time must be stored permanently in a file. Reading a file is slower than reading memory, arrays hold many values without any file, and OUTPUT works directly from variables.
Opening a file FOR WRITE creates a new file, so any existing data in it is lost. Writing after the existing lines is APPEND mode. Text files are written sequentially, so there is no mode that inserts before old lines or overwrites them one at a time.
Birch, Maple and Cedar are longer than 3 characters; their last characters h, e and r are joined to give her. khhemr takes the last character of every line (as if the test were >= 3), BMC takes the first characters instead of the last, and BirchMapleCedar joins whole lines rather than one character from each.
APPEND keeps the existing data and WRITEFILE adds a new line after it, then the file is closed. WRITE would create a new file and lose the old lines, a file opened FOR READ cannot be written to, and READFILE reads a line into a variable rather than writing one.
REPEAT tests its condition after the body, so the first READFILE happens even if EOF is already TRUE: on an empty file there is no line to read. With one or more lines, the REPEAT version reads every line correctly, and a blank line is still a line, so EOF is not TRUE until it has been read.
The file holds A, then A, B. The second OPENFILE ... FOR WRITE creates a new file, so A and B are lost and C is written. APPEND then adds D after C, giving C, D. Four lines would need every open to keep the old data, D alone would mean APPEND also wiped the file, and A, B ignores the last four statements.
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 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.