# File Handling

> Computer Science · CIE A-Level
> Source: https://www.owlsprep.com/study/cie-9618-u11-file-handling/

This module covers core file input/output operations for CIE A-Level Computer Science programming. You will learn to manipulate text and binary files, handle common errors, and implement persistent data storage in programs.

**Prerequisites:** [Procedural programming fundamentals](https://www.owlsprep.com/study/cie-9618-u11-procedural-programming/); [Custom data types and records](https://www.owlsprep.com/study/cie-9618-u10-custom-data-types/)

## Learning objectives

- Follow the full file handling lifecycle: open, process, close files correctly
- Distinguish between text and binary file storage modes
- Implement common file operations like reading, writing and appending
- Handle common file access errors in pseudocode

## Core File Lifecycle: Open, Process, Close

All file operations follow a standard, three-step lifecycle: open the file to get access, perform your read or write operations, then close the file when done. Closing files is critical to free system resources and ensure all in-memory data is written to permanent storage.

**File Mode** — A setting that specifies what operations can be performed on an open file, and how the file content is interpreted.

*Example:* Common modes: read, write, append, text, binary

**Worked example:** Write CIE standard pseudocode to open a text file `scores.txt` in read mode, output the first line to the console, then close the file.

1. Declare a file handle to reference the open file, and a string variable to store the read line:
2. ```
DECLARE FileHandle : FILE
DECLARE FirstLine : STRING
```
3. Open the file in read-only mode:
4. ```
OPENFILE "scores.txt" FOR READ AS FileHandle
```
5. Read the first line, output it, then close the file:
6. ```
READLINE FileHandle, FirstLine
OUTPUT FirstLine
CLOSEFILE FileHandle
```

> **tip**
>
> CIE exam markers always penalize missing `CLOSEFILE` statements in programming questions, so never forget this step.

## Text vs Binary File Modes

Text files store data as sequences of human-readable characters, encoded with standards like ASCII or UTF-8. Binary files store raw binary data directly, which is more compact and preserves the exact size of original data types.

**Worked example:** Compare how the integer 123 is stored in a text file vs a 4-byte integer binary file.

1. In a text file: The integer is converted to three separate characters `'1'`, `'2'`, `'3'`. This takes 3 bytes of storage, and opening the file in a text editor displays the readable text `123`.
2. In a binary file: The raw 4-byte binary value of the integer 123 is stored directly. This takes 4 bytes of storage, and opening the file in a text editor shows unreadable non-printing characters.

> **info**
>
> Theory questions often ask you to calculate file size for text vs binary files, so remember the size difference between the two formats.

## Common File Operations

Beyond basic single-line reads, you will often need to process an entire file line-by-line, append new data to an existing file, or search for a specific entry. The `EOF` (end of file) marker is used to detect when you have reached the end of the file content.

**Worked example:** Write pseudocode to count the total number of lines in a text file called `data.txt`.

1. Initialize a counter to 0, and open the file for reading:
2. ```
DECLARE Count : INTEGER ← 0
DECLARE CurrentLine : STRING
OPENFILE "data.txt" FOR READ
```
3. Loop through the file, reading lines until the end of file is reached, incrementing the counter each iteration:
4. ```
WHILE NOT EOF("data.txt") DO
  READLINE "data.txt", CurrentLine
  Count ← Count + 1
ENDWHILE
```
5. Close the file and output the final count:
6. ```
CLOSEFILE "data.txt"
OUTPUT "Total lines: " + Count
```

**Check your understanding**

Test your understanding:

1. Which mode do you use to add new data to the end of an existing file without deleting its current content?

   - Read mode
   - Write mode
   - Append mode
   - Binary mode

   *Answer:* Append mode

   *Why:* Correct! Append mode adds new data to the end of the file, while write mode overwrites the entire existing file.

## File Error Handling

File operations often fail at runtime for common reasons: the file does not exist, you have incorrect permissions, or the storage device is full. Good programming practice requires checking for these errors and handling them gracefully instead of crashing.

**File Not Found Error** — A common runtime error that occurs when a program tries to open a file that does not exist in the specified path.

**Worked example:** Modify the line counting code above to handle the case where `data.txt` does not exist.

1. After opening the file, add a check to confirm the file exists before processing:
2. ```
OPENFILE "data.txt" FOR READ
IF NOT FILEEXISTS "data.txt" THEN
  OUTPUT "Error: Input file not found"
  STOP
ENDIF
```
3. The rest of the line counting code remains unchanged, but the program outputs a clear error message to the user instead of crashing unexpectedly.

> **Exam tip**
>
> CIE regularly asks for error handling in file operations, so always add a file existence check when opening a file in read mode.

## Common pitfalls

- **Wrong:** Forgetting to close a file after opening it
  - Why it fails: Leaves system resources allocated, and may result in data not being saved to disk
  - Correct: Always add an explicit `CLOSEFILE` statement after finishing work on any open file
- **Wrong:** Using write mode when adding data to an existing file
  - Why it fails: Write mode overwrites the entire existing file, erasing all original content before adding new data
  - Correct: Use append mode when you want to add new data to the end of an existing file
- **Wrong:** Not checking for EOF before reading the next entry
  - Why it fails: Leads to reading garbage data after the end of the file, or runtime errors during execution
  - Correct: Always wrap repeated read operations in a `WHILE NOT EOF()` loop to stop at the end of content
- **Wrong:** Calculating text file size the same way as binary
  - Why it fails: Text files store data as variable-length characters, while binary files use fixed size per data type
  - Correct: For text files, count characters to get size; for binary, multiply number of records by fixed record size
- **Wrong:** Not handling missing files in read mode
  - Why it fails: Examiners expect robust error handling, and will deduct marks for unhandled errors
  - Correct: Always add a `FILEEXISTS` check after opening a file in read mode

## Cheatsheet

| Operation | CIE Pseudocode | Common Use Case |
| --- | --- | --- |
| Open read-only | OPENFILE "f.txt" FOR READ | Read existing file |
| Open write | OPENFILE "f.txt" FOR WRITE | Create/overwrite file |
| Open append | OPENFILE "f.txt" FOR APPEND | Add data to end of file |
| Read line | READLINE handle, lineVar | Read one line of text |
| Write line | WRITELINE handle, data | Write one line of output |
| Check end of file | NOT EOF(handle) | Loop through all content |
| Check file exists | FILEEXISTS "filename" | Handle missing file error |
| Close file | CLOSEFILE handle | Save changes, free resources |

## What's next

File handling is a core foundational skill for both the theory and practical papers of CIE A-Level Computer Science. It is regularly tested in multiple-choice theory questions and forms a core part of most programming practical tasks, so mastering the full file lifecycle is critical for scoring full marks. Once you are comfortable with sequential file handling, you can move on to more advanced storage concepts that build on this foundation. You can also practice error handling more broadly to improve your programming robustness for exams.

- [Object-oriented programming concepts](https://www.owlsprep.com/study/cie-9618-u11-object-oriented-programming-concepts/)
- [Declarative programming concepts](https://www.owlsprep.com/study/cie-9618-u11-declarative-programming-concepts/)
- [Software development](https://www.owlsprep.com/study/cie-9618-u12-overview/)

---

From [OwlsPrep](https://www.owlsprep.com) — free study guides for A-Level, IB, AP and IGCSE, written against the official syllabus. Canonical page: https://www.owlsprep.com/study/cie-9618-u11-file-handling/
