Open, read, write and close files

File Handling (IGCSE 0478 – Section 8.3)

Why use files? (AO2)

  • Store data permanently so it remains after the program stops (e.g., student records, game scores).
  • Work with data sets larger than the computer’s RAM.
  • Share information between different programmes or users.

Four basic file operations (exact syllabus wording)

  • OPEN – establish a connection to a file and select a mode.
  • READ – transfer the next piece of data from the file into a program variable.
  • WRITE – store the contents of a variable (or byte) in the file.
  • CLOSE – release the operating‑system resources and flush any buffered data.

Operation summary (syllabus pseudo‑code)

Operation Syntax (syllabus) Effect
OPEN OPEN <filename> FOR <mode> Creates a file handle and sets the access mode (r, w, a, r+, w+, a+).
READ READ <variable> FROM <file> Gets the next record/byte from the file.
WRITE WRITE <variable> TO <file> Writes a record/byte to the file at the current pointer.
CLOSE CLOSE <file> Closes the handle, flushing buffers and freeing resources.

File modes (what FOR <mode> means)

Mode Purpose (syllabus) Effect on an existing file
r Read only File must already exist; otherwise an error occurs.
w Write only – create or truncate If the file exists it is cleared; if not, a new empty file is created.
a Append – write only, start at end If the file exists data is added to the end; otherwise a new file is created.
r+ Read and write File must exist; reading and writing start at the beginning.
w+ Read and write – create or truncate Existing file is cleared; a new file is created if necessary.
a+ Read and write – append Reading can start anywhere; every write adds data to the end of the file.

Reading from a file

1. Sequential (line‑by‑line) reading – text files

1  OPEN "students.txt" FOR r
2  WHILE NOT EOF
3      READ line FROM file
4      *process line here*
5  END WHILE
6  CLOSE file

2. Random‑access reading – binary files

1  OPEN "data.bin" FOR r
2  SET FILE POINTER TO 100          *move to byte 100*
3  READ value FROM file
4  CLOSE file

3. Byte‑level reading (low‑level I/O)

1  OPEN "image.bin" FOR r
2  READ BYTE b FROM file            *reads a single byte*
3  *use b as required*
4  CLOSE file

Writing to a file

1. Whole‑record (text) writing

1  OPEN "log.txt" FOR w
2  WRITE "Program started" TO file
3  WRITE "User logged in" TO file
4  WRITE "Program finished" TO file
5  CLOSE file

2. Append mode – add without deleting existing data

1  OPEN "log.txt" FOR a
2  WRITE "New session at " + TIME() TO file
3  CLOSE file

3. Byte‑level writing (low‑level I/O)

1  OPEN "output.bin" FOR w
2  WRITE BYTE 0xFF TO file          *writes a single byte*
3  WRITE BYTE 0x00 TO file
4  CLOSE file

Ensuring a file is closed – error‑handling (AO3)

Even if an error occurs, the file must be closed. A simple “finally” style structure is acceptable in the syllabus.

1  IF FILE_EXISTS("data.txt") THEN
2      OPEN "data.txt" FOR r
3      TRY
4          READ line FROM file
5          *process line*
6      CATCH
7          DISPLAY "Read error"
8      FINALLY
9          CLOSE file
10     END TRY
11 END IF

Common file‑handling errors and how to avoid them (AO3)

  1. File not found – occurs when opening in r mode and the file does not exist.
    Prevention: use IF FILE_EXISTS("…") THEN … before opening, or open with w/a to create a new file.
  2. Permission denied – programme lacks rights to read/write the file.
    Prevention: store files in a directory where the user has read/write permission, or change the file’s OS permissions.
  3. End‑of‑file (EOF) reached – trying to read beyond the last record.
    Prevention: always test EOF before a READ operation (as in the sequential‑read loop).
  4. Data‑type mismatch – reading a number as text or vice‑versa.
    Prevention: convert with the appropriate functions, e.g. INT() or STR().

Full worked example – storing and updating student scores

*--- 1. Read existing scores (if the file exists) --------------------*
IF FILE_EXISTS("scores.txt") THEN
    OPEN "scores.txt" FOR r
    scores ← EMPTY LIST
    WHILE NOT EOF
        READ line FROM file                     *format: name,score*
        SPLIT line BY "," → name, scoreStr
        scores.APPEND( name , INT(scoreStr) )
    END WHILE
    CLOSE file
END IF

*--- 2. Add a new record --------------------------------------------*
newName  ← "Alice"
newScore ← 87
scores.APPEND( newName , newScore )

*--- 3. Write all records back – overwrite the file -----------------*
OPEN "scores.txt" FOR w
FOR EACH rec IN scores
    WRITE rec.name + "," + STR(rec.score) TO file
END FOR
CLOSE file

Key points to remember (exam‑style checklist)

  • Always OPEN a file before READ or WRITE.
  • Choose the correct FOR <mode> – it decides whether the file is created, cleared, or appended to.
  • Read data in exactly the same format it was WRITEn (text vs. binary, line delimiters, separators).
  • Never omit CLOSE; it finalises the operation and frees resources.
  • Test EOF before each READ to avoid reading past the end.
  • Use FILE_EXISTS when opening a file in r mode.
  • Handle possible errors with a TRY … CATCH … FINALLY structure so the file is always closed.

Exam checklist (AO1–AO3)

  1. State the four basic file operations using the exact syllabus syntax.
  2. Explain the difference between the six file modes (r, w, a, r+, w+, a+) and their effect on an existing file.
  3. Write correct pseudo‑code to read a text file line by line, including EOF testing.
  4. Write correct pseudo‑code to create a new file and write three separate lines (show both w and a examples).
  5. Describe why CLOSE is essential, and give an example of closing a file in a FINALLY block.
  6. Identify two common file‑handling errors and give one method to avoid each.

Create an account or Login to take a Quiz

38 views
0 improvement suggestions

Log in to suggest improvements to this note.