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
Keyword
Usage
Description
OPENFILE
OPENFILE "file.txt" FOR READ
Opens a file for reading (from start). File must exist.
OPENFILE
OPENFILE "file.txt" FOR WRITE
Opens for writing. Creates new or overwrites existing.
OPENFILE
OPENFILE "file.txt" FOR APPEND
Opens for adding records to the end. Does not overwrite.
READFILE
READFILE "file.txt", data
Reads the next line/record from an open file into a variable.
WRITEFILE
WRITEFILE "file.txt", data
Writes a value/line to an open file.
CLOSEFILE
CLOSEFILE "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 NOTEOF("students.txt") READFILE"students.txt", line OUTPUTline 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 NOTEOF("data.txt") READFILE"data.txt", record processRecord(record) ENDWHILE EXCEPTFileNotFoundException OUTPUT"Error: data.txt not found" EXCEPTIOException 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!
Term
Definition
🎯
Mini Test — 4.2.4 File Handling
10 questions · 10 marks · 10 minutes
⏱ 10:00
Section A — Multiple Choice [5 marks]
Q1A program needs to add new records to the end of an existing log file without deleting any previous entries. Which file mode should be used?
Q2What does the EOF() function return when the last record in a file has been read?
Q3Which statement correctly opens "data.txt" for reading in Cambridge 9618 pseudocode?
Q4Why is it important to call CLOSEFILE after processing is complete?
Q5Which access method must read all preceding records before accessing a specific record?
Section B — Short Answer [5 marks]
Q6Write pseudocode to create a file "names.txt" and write three names to it: "Alice", "Bob", "Carol".
Mark schemeOPENFILE "names.txt" FOR WRITE [1]; WRITEFILE "names.txt", "Alice" [0.5]; WRITEFILE "names.txt", "Bob" [0.5]; WRITEFILE "names.txt", "Carol" [0.5]; CLOSEFILE "names.txt" [0.5] — total: OPENFILE [1] + WRITEFILE x3 [1] + CLOSEFILE [1] = 3 marks. Use WRITE not APPEND since creating a new file.
Q7Explain what serialisation is and give one use case where it is important.
Mark schemeSerialisation is the conversion of an object (stored in memory with its attributes and state) into a sequence of bytes so it can be saved to a file or sent over a network [1]; deserialisation is the reverse — reconstructing the object from the bytes [1]; use case: saving a game state — the Player object with its position, health, inventory is serialised to a save file; when the game is reopened, the object is deserialised back into memory restoring the exact state [1]. Accept: sending objects between computers over a network; caching complex objects to disk.
Q8Explain the difference between sequential access and random access for files. State one advantage of each.
Mark schemeSequential: records are read from the beginning of the file in order; to access record 100, records 1-99 must be read first [1]; advantage: simple to implement; efficient when ALL records need to be processed [1]; Random: any record can be accessed directly by calculating its position (requires fixed-length records) [1]; advantage: fast for accessing individual records; no need to read all preceding records [1].
Q9A text file stores the number 1000 and a binary file stores the same integer. Explain how the storage differs between the two file types.
Mark schemeIn a text file, 1000 is stored as the character codes for '1', '0', '0', '0' — four separate ASCII character bytes [1]; in a binary file, 1000 is stored as a binary integer directly (e.g. 00000000 00000000 00000011 11101000 in a 4-byte signed integer representation) — still 4 bytes but the same regardless of the number's digit count [1]; advantage of binary: 1 billion stored as '1','0','0','0','0','0','0','0','0','0' is 10 bytes in text but still 4 bytes in binary — binary is more compact for large numbers [1].
Q10Describe the purpose of a stream in file I/O. Distinguish between an input stream and an output stream.
Mark schemeA stream is an abstraction representing a flow of data between a source and a destination; it provides a standardised way for programs to read and write data regardless of whether the source/destination is a file, keyboard, network socket, or other device [1]; input stream: data flows INTO the program — e.g. reading from a file (READFILE), reading keyboard input (INPUT/USERINPUT); the program receives data from the stream [1]; output stream: data flows FROM the program — e.g. writing to a file (WRITEFILE), writing to the console (OUTPUT); the program sends data into the stream [1].