Pro Content

Upgrade to access file handling, streams, and all Cambridge 9618 lessons.

Upgrade to Pro →
← Back to Dashboard
📗 Paper 4 · 4.2 Further OOP
4.2.4 File Handling & Streams
Cambridge 9618 · International A Level Computer Science · ~15 min read
Notes
Video
Slides
Quiz
Worksheet

Text Files vs Binary Files

All persistent data is stored in files. There are two main categories:

📄 Text Files
Store data as human-readable ASCII/Unicode characters. Each line ends with a newline character. Can be opened and read in any text editor. Larger than binary for numeric data (integer 1000 stored as '1','0','0','0' — 4 bytes). Extension: .txt, .csv, .html, .py
🗂 Binary Files
Store data in raw binary format — exactly as it exists in memory. NOT human-readable (opening in a text editor shows garbled characters). Smaller and faster for structured data. Extension: .exe, .jpg, .mp3, .db, .bin

File Access Methods

📋 Sequential (Serial) Access
Records are read from the beginning of the file, one by one, in order. To reach a specific record, all preceding records must be read first. Simple to implement. Efficient for processing ALL records. Used for: log files, payroll processing, batch processing. Cambridge pseudocode: OPENFILE, READFILE, EOF loop.
🎯 Random (Direct) Access
Any record can be accessed directly without reading preceding records. Requires fixed-length records (so the position of any record can be calculated). Fast for finding a specific record. Used for: databases, large customer record systems. Not covered in 9618 Cambridge pseudocode directly — more relevant to A Level databases.

Cambridge 9618 File Handling Keywords

KeywordUsageDescription
OPENFILEOPENFILE "file.txt" FOR READOpens a file for reading (from start). File must exist.
OPENFILEOPENFILE "file.txt" FOR WRITEOpens for writing. Creates new or overwrites existing.
OPENFILEOPENFILE "file.txt" FOR APPENDOpens for adding records to the end. Does not overwrite.
READFILEREADFILE "file.txt", dataReads the next line/record from an open file into a variable.
WRITEFILEWRITEFILE "file.txt", dataWrites a value/line to an open file.
CLOSEFILECLOSEFILE "file.txt"Closes the file, flushing the buffer and freeing the resource.
EOF()EOF("file.txt")Returns TRUE when all records have been read (End of File reached).

File Modes: READ, WRITE, APPEND

READ
Opens file for reading only. Starts at the beginning. File must already exist — error if not found. Cannot write to a READ file.
WRITE
Creates a new file. If file already exists, it is completely overwritten (old content lost). Starts writing from position 0. Cannot read from a WRITE file.
APPEND
Opens existing file; new data is added AFTER the existing content. File is created if it doesn't exist. Existing content is preserved. Used for logs, histories.

Reading a File — Complete Pattern

// Pattern: open → loop while not EOF → read → process → close
OPENFILE "students.txt" FOR READ
WHILE NOT EOF("students.txt")
  READFILE "students.txt", line
  OUTPUT line
ENDWHILE
CLOSEFILE "students.txt"

Writing to a File

// Writing new data (overwrites if file exists)
OPENFILE "results.txt" FOR WRITE
WRITEFILE "results.txt", "Alice,95"
WRITEFILE "results.txt", "Bob,87"
WRITEFILE "results.txt", "Carol,92"
CLOSEFILE "results.txt"

// Appending — add to end without losing existing records
OPENFILE "results.txt" FOR APPEND
WRITEFILE "results.txt", "David,78"
CLOSEFILE "results.txt"

File Handling with Exception Handling

File operations can fail (file missing, disk full, permission denied). Combining file handling with TRY-EXCEPT ensures proper error handling and guaranteed file closure in FINALLY:

TRY
  OPENFILE "data.txt" FOR READ
  WHILE NOT EOF("data.txt")
    READFILE "data.txt", record
    processRecord(record)
  ENDWHILE
EXCEPT FileNotFoundException
  OUTPUT "Error: data.txt not found"
EXCEPT IOException
  OUTPUT "File read error"
FINALLY
  CLOSEFILE "data.txt"  // always close the file
ENDTRY

EOF Marker

A text file has a special End-of-File (EOF) marker at its end — a special character (often ASCII 26) that indicates there is no more data. The EOF() function returns TRUE when this marker is reached, allowing a WHILE loop to stop reading.

File contents:   Alice,95↵ Bob,87↵ Carol,92↵ EOF

WHILE NOT EOF("results.txt") → reads Alice, Bob, Carol → EOF reached → loop ends

Streams

A stream is a flow of data between a source (where data comes from) and a destination (where data goes). All file operations, keyboard input, and console output work through streams. Key concepts:

  • Input stream — data flows INTO the program (reading a file, keyboard input)
  • Output stream — data flows FROM the program (writing to a file, screen output)
  • Buffer — a temporary memory area that holds data between the program and the file/device; improves efficiency by reading/writing in blocks rather than byte-by-byte
  • Flushing — forcing buffered data to be written to the actual file; CLOSEFILE flushes and closes the stream

Serialisation

Serialisation is the process of converting an object (in memory) into a sequence of bytes that can be stored in a file or transmitted over a network. Deserialisation is the reverse — reconstructing the object from the bytes. This allows complex objects (with multiple attributes) to be saved and restored.

Cambridge 9618 exam tip: Know all five keywords: OPENFILE, READFILE, WRITEFILE, CLOSEFILE, EOF(). Know the three modes: READ (existing file, read only), WRITE (overwrite/create new), APPEND (add to end, preserve existing). The standard loop pattern is: OPENFILE → WHILE NOT EOF → READFILE → process → ENDWHILE → CLOSEFILE. Always explain WHY CLOSEFILE is important: flushes the buffer to disk and releases the file handle so other processes can access the file. APPEND is commonly tested: "add a new record without losing existing data" → use APPEND mode.
⚠️ Common Mistakes
  • Using FOR WRITE when you mean APPEND — WRITE mode destroys all existing content and starts fresh. APPEND adds to the end without deleting anything. Always choose the correct mode for the task.
  • Not calling CLOSEFILE — leaving a file open wastes system resources (file handles), may prevent other programs from accessing it, and importantly: buffered data may not be written to disk until the file is closed.
  • Reading past EOF — not checking EOF() before READFILE can cause an error when the end of file is reached. Always use WHILE NOT EOF() before each READFILE call.
  • Forgetting to OPENFILE before READFILE/WRITEFILE — you cannot read or write to a file without first opening it. The file must be explicitly opened with the correct mode.
  • Mixing read/write without closing and reopening — in Cambridge pseudocode, a file opened FOR READ cannot be written to, and vice versa. To both read then write, close and reopen with the different mode.
  • Confusing APPEND and WRITE return behaviour — WRITE mode is useful when creating a file from scratch each time (e.g. generating a report); APPEND is for logs and histories where data accumulates over time.
✅ Notes completed!
Video coming soon
Click slide or press arrow keys to navigate

Worksheet — 4.2.4 File Handling

8 questions · Cambridge 9618 standard

Q1State the difference between READ, WRITE, and APPEND file modes. Give one use case for each.[6]
✅ Mark scheme
READ: opens an existing file for reading from the beginning; file must exist; cannot write to it; use case: processing student records from a file [1][1]; WRITE: creates a new file or completely overwrites an existing one; starts at position 0; cannot read from it; use case: generating a fresh report file each time [1][1]; APPEND: opens existing file and adds new records to the end; existing content is preserved; use case: adding new entries to an error log without deleting previous entries [1][1].
Q2Write pseudocode to read all lines from a file "scores.txt" and output each line. Ensure the file is always closed even if an error occurs.[5]
✅ Mark scheme
TRY block [1]; OPENFILE "scores.txt" FOR READ [1]; WHILE NOT EOF("scores.txt") followed by READFILE "scores.txt", line and OUTPUT line [1]; ENDWHILE; EXCEPT IOException with appropriate message [1]; FINALLY CLOSEFILE "scores.txt" [1]. Full marks for correct structure with all five elements. Award partial marks: 1 for correct OPENFILE, 1 for correct WHILE/EOF/READFILE loop, 1 for CLOSEFILE in FINALLY.
Q3Explain the role of the EOF() function in file reading. What happens if you try to READFILE when EOF has been reached?[3]
✅ Mark scheme
EOF() returns TRUE when the end-of-file marker has been reached — meaning all records have been read and there is no more data to read [1]; it is used in a WHILE NOT EOF() loop to control reading — the loop continues reading records as long as EOF is FALSE, and exits when EOF becomes TRUE [1]; if READFILE is called when EOF has already been reached, an error/exception is thrown — there is no more data to read, so the operation fails; this is why EOF must be checked before each READFILE call [1].
Q4A program keeps an error log file. New errors should be added without deleting the existing log. Write pseudocode to add the message "Disk space low" to "error.log".[3]
✅ Mark scheme
OPENFILE "error.log" FOR APPEND [1]; WRITEFILE "error.log", "Disk space low" [1]; CLOSEFILE "error.log" [1]. Must use APPEND (not WRITE — which would delete existing log entries). Award 2/3 if WRITE is used but all other elements are correct — note error about mode.
Q5Explain what a "buffer" is in the context of file I/O and why CLOSEFILE is important.[3]
✅ Mark scheme
A buffer is a temporary area of memory between the program and the file storage device; data being written is first held in the buffer rather than written to the file byte-by-byte — this improves performance [1]; WRITEFILE writes to the buffer; data may not reach the physical file until the buffer is full or explicitly flushed [1]; CLOSEFILE is important because: it flushes the buffer — guaranteeing all buffered data is written to the actual file; it releases the file handle so the operating system can make it available to other programs; without CLOSEFILE, data in the buffer may be lost if the program terminates [1].
Q6State two differences between text files and binary files. State one advantage and one disadvantage of binary files compared to text files.[4]
✅ Mark scheme
Difference 1: text files store data as human-readable characters (ASCII/Unicode); binary files store data in raw binary format as it exists in memory [1]; Difference 2: text files can be opened and read in any text editor; binary files appear as garbled characters if opened in a text editor [1]; Binary advantage: more compact/smaller for structured numeric data (integer stored as 4 bytes vs "1000" taking 4 bytes per character in text); faster to read/write [1]; Binary disadvantage: not human-readable — cannot be easily inspected or edited manually; requires the program that wrote it (or knows its structure) to interpret it [1].
Q7A program logs user activity. Write pseudocode to OPENFILE "log.txt" FOR APPEND, write the string "User logged in" to it, then CLOSEFILE. Explain why APPEND mode is used rather than WRITE mode for a log file.[4]
✅ Mark scheme
OPENFILE "log.txt" FOR APPEND [1]; WRITEFILE "log.txt", "User logged in" [1]; CLOSEFILE "log.txt" [1]; WRITE mode overwrites existing content / APPEND mode adds to end of file without losing previous entries — essential for a log that must accumulate records [1].
Q8Explain the purpose of closing a file after reading or writing. What risk does a program face if a file is not explicitly closed, and how does buffering relate to this?[4]
✅ Mark scheme
Closing a file releases the file handle / frees the resource so other processes can access it [1]; data written to a file may be held in a buffer in memory before being written to disk [1]; if the file is not closed, buffered data may not be flushed / some or all data may be lost [1]; explicitly closing the file forces the buffer to be written to disk, ensuring data integrity [1].
Topic Quiz
Question 1 of 10
You scored
out of 10
Card 1 of 8
Click to reveal definition
🎉
All cards reviewed!
TermDefinition
🎯

Mini Test — 4.2.4 File Handling

10 questions · 10 marks · 10 minutes

← 4.2.3 Exception Handling
71 of 82 · Cambridge 9618
4.3.1 Stacks & Queues →