CIE IGCSE | 8.3.2.1 Open, Read and Close a Text File

Lesson objective

Open a text file in READ mode, read data into variables in sequence, close the file when finished, and trace repeated reads without changing its contents.

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.

Students.txt contains exactly these three name lines
Illustration line numberStored line of text
1Maya
2Leo
3Aisha

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
These reads assume the file has already been opened at its beginning
ReadStudentName afterwardsNext unread line
FirstMayaLeo
SecondLeoAisha
ThirdAishaNo 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

  1. Maya
  2. Leo
  3. 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.

    MATCH THE READING INSTRUCTION TO ITS ROLE

    Terminology

    Terminology

    OPENFILE

    Opens the named file for a specified mode of access.

    READ mode

    Access intended to read existing file data.

    READFILE

    Reads a data item and assigns it to the specified destination variable.

    CLOSEFILE

    Ends access to a file when it is no longer needed.

    File identifier

    The filename expressed as a STRING literal or variable.

    Destination variable

    The working storage receiving a read value.

    Read position

    The position of the next data item to be read sequentially.

    Sequential reading

    Receiving successive data items in their stored order.

    Text line

    A line of character data in the file format used here.

    OUTPUT

    Displays a current value; separate from file reading.

    End of file

    The state when no more data remains to read.

    Known-count reading

    A fixed number of reads based on an explicit file-length assumption.

    Initialised array element

    An element that has received a value before use.

    File format

    The arrangement and interpretation expected for stored data.

    Blank line

    A line with no text content, distinct from the absence of a next line.

    Input conversion

    Interpreting represented data as the required type.

    Accessible file

    A file present at a usable location with suitable access permission.

    Reading simulation

    An illustration of read state changes, not actual device-file access.

    Questions

    Questions

    CHECK YOUR UNDERSTANDING

    Select all correct choices. Each exact set earns one point.

    1. Which establish correct reading access?
    2. What does READFILE "Students.txt", StudentName do?
    3. The file contains Maya, Leo, Aisha. After two reads into the same variable, which apply?
    4. Which statements about CLOSEFILE are correct?
    5. Which support one continuous three-line pass?
    6. Why read into StudentNames[Position]?
    7. Which are correct for a file with exactly three names?
    8. Which distinguish filenames and destinations?

    EXPLAIN AND COMPARE

    Write your answers before revealing each sample.

    1. Describe the open, read and close sequence for a text file.

    2. Trace three reads of Maya, Leo and Aisha into one variable.

    3. Explain why reading does not delete the source data.

    4. Explain why OPENFILE should normally be outside a continuous reading loop.

    5. Explain what remains after CLOSEFILE.

    6. Suggest how to retain all three names for later processing.

    7. Explain why a fixed three-read loop is unsuitable for arbitrary unknown-length files.

    8. Compare READFILE and INPUT in this context.

    BUILD IT | LOAD TWO TASKS

    Tasks.txt exists and contains exactly two lines: “Revise arrays” and “Check file handling”. Declare a STRING array Tasks indexed one to two. Open the file for reading, load one line into each element using a loop, close the file and then output the two tasks from the array. Explain why the second loop still works after the close.

    Reveal one possible solution
    DECLARE Tasks : ARRAY[1:2] OF STRING
    DECLARE Position : INTEGER
    OPENFILE "Tasks.txt" FOR READ
    FOR Position ← 1 TO 2
      READFILE "Tasks.txt", Tasks[Position]
    NEXT Position
    CLOSEFILE "Tasks.txt"
    FOR Position ← 1 TO 2
      OUTPUT Tasks[Position]
    NEXT Position

    The outputs are “Revise arrays” and “Check file handling”. The names have been copied into the array’s working elements, so closing the source file does not erase those assigned values. The two reads rely on the stated two-line format.

    Flashcards

    Flashcards

    Click to flip. Select the ideas you need to revisit.

    0 cards selected for revision.

      Selections are kept while this page is open.

      Workbook

      Workbook

      COMING SOON

      The workbook for 8.3.2.1 Open, Read and Close a Text File is coming soon. Complete the matching task and written questions in your exercise book.