Learn
8.3.2.1 | OPEN, READ AND CLOSE A TEXT FILE
01 | LOAD A LIST WITHOUT RETYPING IT
A teacher has saved three student names in Students.txt: Maya, Leo and Aisha, one name per line. A program needs to display those names without asking the user to type them again.
The program must open the file for reading, read its data into working variables and close the file when finished. These are explicit operations; declaring a variable or writing the filename on its own does not load the data.
A text file stores data represented as characters. In this lesson each line contains one name, so each read in our examples receives one line of text.
02 | KNOW THE SOURCE FILE
The filename identifies the saved data source. Students.txt is STRING text in the file-handling instructions, so it is enclosed in double quotes when written directly.
The line numbers below help us explain reading order. They are labels in the illustration, not extra text stored in the file. The stored contents are the three names.
| Illustration line number | Stored line of text |
|---|---|
| 1 | Maya |
| 2 | Leo |
| 3 | Aisha |
03 | OPENFILE PREPARES THE FILE FOR READING
OPENFILE identifies the file and states its mode: the kind of operation permitted. FOR READ means the program intends to read existing data.
Opening prepares access to the file; it does not output a name or assign every line to a variable. The first read is still needed.
READ mode does not erase the stored contents. Do not use WRITE mode to load a file: Cambridge specifies that opening FOR WRITE creates a new file and loses any existing data for that file.
OPENFILE "Students.txt" FOR READ
04 | READFILE ASSIGNS THE NEXT ITEM TO A VARIABLE
READFILE gives the file identifier and a destination variable, separated by a comma. Declare the variable with a suitable type before using it.
With this file’s one-name-per-line layout, the first read receives “Maya” and assigns it to StudentName. The name comes from the file, not from a new keyboard input.
READFILE does not itself display the received name. OUTPUT StudentName is a separate instruction that displays the variable’s current value.
DECLARE StudentName : STRING OPENFILE "Students.txt" FOR READ READFILE "Students.txt", StudentName OUTPUT StudentName CLOSEFILE "Students.txt"
05 | THE READ POSITION ADVANCES
The read position tracks which item will be read next during sequential reading. After the first name is read, the next read receives Leo, not Maya again.
A second read into StudentName replaces its earlier value. The file’s saved names remain unchanged: reading copies data into working memory rather than removing it from storage.
Think of a bookmark moving through the file. The bookmark changes; the text on the page does not. This is a model of sequential access, not a claim that an application stores a visible bookmark in the file.
READFILE "Students.txt", StudentName OUTPUT StudentName READFILE "Students.txt", StudentName OUTPUT StudentName
| Read | StudentName afterwards | Next unread line |
|---|---|---|
| First | Maya | Leo |
| Second | Leo | Aisha |
| Third | Aisha | No more lines |
06 | REUSING A VARIABLE DOES NOT KEEP ALL THE NAMES
StudentName stores the most recently assigned name. After reading all three into that same variable, its value is Aisha. Maya and Leo are not still stored in that one STRING variable.
Outputting immediately after each read displays every name while it is available. If the program must use all names later, it needs additional working storage, such as an array.
Do not confuse retaining the names in the source file with retaining them all in the current variable. The file still contains the original three lines.
07 | CLOSEFILE ENDS THAT FILE ACCESS
CLOSEFILE closes the file when the program no longer needs the open access. It helps release the associated resources and marks the end of this reading task.
Closing does not delete the file, clear its stored contents or automatically erase the variable that received data. StudentName can still hold the last read name while the program continues.
Do not attempt more READFILE operations through the closed access. Open the file again if another reading task is needed. A file should be opened in only one mode at a time.
CLOSEFILE "Students.txt" OUTPUT StudentName
08 | FOLLOW THE COMPLETE THREE-LINE READ
Because this example file is known to contain exactly three name lines, a FOR loop can perform exactly three reads. LineNumber controls repetition; StudentName receives the data.
The outputs are Maya, Leo and Aisha, then “Names loaded”. OPENFILE and CLOSEFILE are outside the loop because we want one continuous pass through the file.
Putting a fresh open-and-close pair inside every iteration would start a new read task each time instead of continuing through the existing sequential read.
DECLARE StudentName : STRING DECLARE LineNumber : INTEGER OPENFILE "Students.txt" FOR READ FOR LineNumber ← 1 TO 3 READFILE "Students.txt", StudentName OUTPUT StudentName NEXT LineNumber CLOSEFILE "Students.txt" OUTPUT "Names loaded"
09 | STEP THROUGH OPEN, READ, OUTPUT AND CLOSE
The simulation shows the saved lines, the next unread line and StudentName. Read and output are separate steps, so you can see that receiving data is different from displaying it.
SAVED CONTENTS OF Students.txt
- Maya
- Leo
- Aisha
This is a simulation of the supplied three-line file. It does not access files on your device. The highlighted saved line is the next one to be read; after the final read, no saved line is highlighted.
10 | READ INTO AN ARRAY FOR LATER USE
StudentNames : ARRAY[1:3] OF STRING can retain all three names in working memory. The index Position selects which element receives each line.
After the first loop, [1] holds Maya, [2] Leo and [3] Aisha. The file can be closed before a second loop displays the array, because the values have already been copied into the program’s working storage.
The array declaration does not load the names by itself. Each READFILE assigns one element, and the loop must match both the known file layout and the array bounds.
DECLARE StudentNames : ARRAY[1:3] OF STRING DECLARE Position : INTEGER OPENFILE "Students.txt" FOR READ FOR Position ← 1 TO 3 READFILE "Students.txt", StudentNames[Position] NEXT Position CLOSEFILE "Students.txt" FOR Position ← 1 TO 3 OUTPUT StudentNames[Position] NEXT Position
11 | A FILENAME CAN BE SUPPLIED BY A STRING VARIABLE
The file identifier can also be a STRING variable holding the filename. Use that variable consistently for the open, read and close operations.
FileName holds “Students.txt”. Writing FileName without quotes uses that stored value. Writing "FileName" instead would refer to a file literally named FileName.
A filename or path must identify an accessible location in the program’s environment. A correct-looking name does not guarantee the file exists.
DECLARE FileName : STRING DECLARE StudentName : STRING FileName ← "Students.txt" OPENFILE FileName FOR READ READFILE FileName, StudentName CLOSEFILE FileName OUTPUT StudentName
12 | DO NOT READ PAST THE AVAILABLE DATA
End of file means no more data remains for the sequential read. Our three-line example permits three reads, not an unlimited number.
A fourth read has no next name to supply. Do not assume it automatically repeats Aisha, returns a useful default or wraps to Maya. The exact response depends on the environment.
Our fixed-count loops rely on the explicit assumption that three lines exist. For an unknown-length file, use the environment’s appropriate end-of-file checking and error-handling mechanism. Do not guess the length or silently treat a fixed count as general-purpose reading code.
13 | INTERPRET DATA ACCORDING TO ITS FORMAT
A name line is naturally read into STRING. A line containing the characters “12” represents numeric data only if the program interprets it according to the expected format and type.
Do not assume arbitrary text becomes a valid number simply because it came from a file. Programs must handle conversion and validation appropriately for the language and file format they use.
A blank line is still a line of text and may represent an empty STRING in a line-reading format. It is not automatically the same as end of file. The reading logic must follow the actual format’s rules.
14 | CHECK THE OPERATION SEQUENCE
Read before opening: establish READ access before READFILE. Wrong mode: WRITE is for writing and can destroy existing content, so use READ when loading.
Close too early: finish the intended reads before closing. Too many reads: check the known count or use an appropriate end-of-file strategy.
Quoted destination: StudentName is a variable destination, not the literal text "StudentName". Assuming output: READFILE assigns data; OUTPUT displays it.
Real programs must also handle a missing or inaccessible file and unsuitable contents. The simple examples here assume the stated file exists and contains the expected lines.
15 | EXPLAIN WHAT CHANGES AND WHAT REMAINS
A useful explanation is: “OPENFILE prepares Students.txt for reading. Each READFILE assigns the next name to StudentName and advances the read position. OUTPUT displays that variable, and CLOSEFILE ends the file access.”
The working variable and read position change during reading. The saved file contents do not. Closing the file does not prevent the program from using values it has already stored in variables or arrays.
The next lesson covers writing data to text files, where the program explicitly changes saved content rather than only reading it.