# Sequential File Handling (OPENFILE, READFILE, WRITEFILE)

- **Track:** Cambridge IGCSE™ Computer Science (0478 / 0984) (CAMBRIDGE IGCSE 0478)
- **Module:** Section 8: Programming Concepts & File Handling
- **Estimated Duration:** 20 minutes
- **Access:** Open Theory (All-Access for Interactive IDE &amp; Autotests)

---

## Theory & Conceptual Background

In computer systems, variables held in primary storage (RAM) are **volatile**; their contents are lost when the program terminates or when power is turned off. To retain data between program runs, programs store information on secondary storage devices in **files**.

---

## 1. What is a Sequential File?

A **sequential file** stores data records in serial order, one after another from the beginning to the end.

- To access the 50th record in a sequential file, a program must read through records 1 through 49 first.
- EOF is the condition that no unread records remain. It need not be a physical marker stored in the file.

---

## 2. Cambridge Pseudocode File Operations

Cambridge pseudocode defines standard primitives for managing sequential text files:

### 1. Opening a File (`OPENFILE`)

Before any file operations can take place, the file must be opened in an explicit mode:

```pseudocode
OPENFILE <Filename> FOR <Mode>
```

  
| Mode | Purpose | Behavior with Existing Files |
| --- | --- | --- |
| **`READ`** | Used to retrieve data from an existing file. | Generates an error if the file does not exist. Does not alter file contents. |
| **`WRITE`** | Used to create a new file or overwrite an existing file. | If the file already exists, all previous data is **erased** (overwritten). |
| **`APPEND`** | Used to add new records to an existing file. | Preserves existing data and positions the file pointer at the very end. |

### 2. Reading from a File (`READFILE`)

Retrieves the next line or record from an open file and stores it in a declared variable:

```pseudocode
READFILE <Filename>, <Variable>
```

### 3. Writing to a File (`WRITEFILE`)

Appends or writes a line or record of data into an open file:

```pseudocode
WRITEFILE <Filename>, <DataExpression>
```

### 4. Detecting End of File (`EOF`)

A built-in Boolean function that returns `TRUE` if the file pointer has reached the end of the file, or `FALSE` if more records remain to be read:

```pseudocode
EOF(<Filename>)
```

### 5. Closing a File (`CLOSEFILE`)

Releases the system handle on the file, flushes any unwritten buffers to physical storage, and makes the file available to other processes:

```pseudocode
CLOSEFILE <Filename>
```

---

## 3. The Standard Sequential Read Pattern

Because the number of records in a file is typically not known in advance, a **pre-condition `WHILE` loop** combined with `NOT EOF(...)` is the standard pattern:

```pseudocode
DECLARE StudentName : STRING
DECLARE RecordCount : INTEGER

RecordCount <- 0

OPENFILE "ClassList.txt" FOR READ

WHILE NOT EOF("ClassList.txt") DO
    READFILE "ClassList.txt", StudentName
    OUTPUT "Student: ", StudentName
    RecordCount <- RecordCount + 1
ENDWHILE

CLOSEFILE "ClassList.txt"

OUTPUT "Total students registered: ", RecordCount
```

### Why `WHILE NOT EOF` is used:

1. **Handles empty files safely**: If `ClassList.txt` is empty, `EOF` is immediately `TRUE`. The loop condition `NOT EOF` evaluates to `FALSE`, preventing the program from executing `READFILE` on an empty file.
2. **Handles variable lengths**: The loop terminates automatically when the last record has been processed, regardless of whether the file contains 5 or 5,000 records.

---

## 4. The Standard Sequential Write and Append Patterns

### Writing New Data (Overwriting):

```pseudocode
OPENFILE "Results.txt" FOR WRITE
WRITEFILE "Results.txt", "Exam Session: June 2026"
WRITEFILE "Results.txt", "Grade: A*"
CLOSEFILE "Results.txt"
```

### Appending Data (Preserving Existing Content):

```pseudocode
OPENFILE "AuditLog.txt" FOR APPEND
WRITEFILE "AuditLog.txt", "User Admin logged in at 14:02"
CLOSEFILE "AuditLog.txt"
```

---

## 5. Common Pseudocode Mistakes in File Handling

1. **Omitting `CLOSEFILE`**: Failing to close a file can leave buffered data unwritten to disk or lock the file from subsequent access.
2. **Confusing `WRITE` with `APPEND`**: Using `FOR WRITE` when intending to add records destroys all previous data in the file.
3. **Using `INPUT` or `OUTPUT` instead of `READFILE` / `WRITEFILE`**: `INPUT` and `OUTPUT` interact with the user via the console; `READFILE` and `WRITEFILE` interact with persistent storage files.
4. **Reading past the end**: Use `WHILE NOT EOF` when the record count is unknown. A `FOR` loop is suitable when the exact number of available records is known.

---

## Interactive Exercises & Autotest Specifications

### Exercise 1: Exam-Style Check: File Access Modes in Pseudocode (Multiple choice, 30 XP)

**Instructions:**
A program needs to add new customer log entries to an existing file `CustomerLog.txt` without deleting previous entries. Which file opening mode must be used?

**Options:**
- **A**: OPENFILE &quot;CustomerLog.txt&quot; FOR APPEND
- **B**: OPENFILE &quot;CustomerLog.txt&quot; FOR WRITE
- **C**: OPENFILE &quot;CustomerLog.txt&quot; FOR READ
- **D**: OPENFILE &quot;CustomerLog.txt&quot; FOR MODIFY


**Autotest Expectations:**
- **Correct file opening mode APPEND identified**: `selection_match` -> Expected: `opt_append`

### Exercise 2: Exam-Style Question: Sequential File Reading Operations (Fill in blank, 35 XP)

**Instructions:**
Fill in the missing Cambridge pseudocode keywords to complete the sequential file reading loop:


**Starter Code:**
```text
{"prompt":"Fill in the missing Cambridge pseudocode keywords to complete the sequential file reading loop:","template":"```pseudocode\nDECLARE ItemRecord : STRING\n\nOPENFILE \"Inventory.txt\" FOR [blank_1]\nWHILE NOT [blank_2](\"Inventory.txt\") DO\n    [blank_3] \"Inventory.txt\", ItemRecord\n    OUTPUT ItemRecord\nENDWHILE\n[blank_4] \"Inventory.txt\"\n```","word_bank":["READ","EOF","READFILE","CLOSEFILE","WRITE","OPENFILE","INPUT","APPEND"]}
```

**Autotest Expectations:**
- **File mode READ**: `text_exact` -> Expected: `READ`
- **End of file function EOF**: `text_exact` -> Expected: `EOF`
- **File read statement READFILE**: `text_exact` -> Expected: `READFILE`
- **File close statement CLOSEFILE**: `text_exact` -> Expected: `CLOSEFILE`

### Exercise 3: Independent Practice: Save and read records (Pseudocode, 30 XP)

**Instructions:**
Read two text lines. Save them to Records.txt using WRITE mode, close the file, reopen it for READ and output each record in order until EOF. Close the file after reading.

Write a complete program. Read inputs in the stated order. Output only the requested results, one per line, without input prompts. Test with your own values before submitting.


**Starter Code:**
```text
// Plan your solution, then write your program.

```

**Autotest Expectations:**
- **Text with spaces**: `test_case` -> Expected: `{&quot;inputs&quot;:[&quot;Green team&quot;,&quot;Blue team&quot;],&quot;output&quot;:&quot;Green team\nBlue team&quot;}`
- **Different records**: `test_case` -> Expected: `{&quot;inputs&quot;:[&quot;One&quot;,&quot;Two&quot;],&quot;output&quot;:&quot;One\nTwo&quot;}`

