💾 Programming Topic 8.3: File Handling - Saving Your Work Permanently!

Welcome to the File Handling chapter! Up until now, when your program runs, any data you input (like a score, a name, or a calculation result) is typically stored in variables in RAM (Random Access Memory).

The problem? As soon as the program ends, that data disappears forever! This isn't useful for applications like high-score tables, address books, or user account systems.

File handling is the crucial process that lets your programs save data permanently onto secondary storage (like a hard drive or SSD). This means the data persists and can be used again the next time the program runs.


1. The Purpose of File Handling (8.3.1)

The fundamental idea behind using files is to achieve persistence. Persistence simply means the data remains saved even after the program has stopped running and the computer is turned off.

Analogy: The Computer's Filing Cabinet

Think of your program as a temporary worker in an office. Variables are like sticky notes—easy to use, but they disappear when the office closes.

Files, however, are like filing cabinets stored in a secure location. To save or retrieve important information, the program must follow a specific process:

  • Get the key (OPEN the file).
  • Put the information in or take it out (WRITE or READ the file).
  • Lock the cabinet (CLOSE the file).

Key Takeaway: Files provide permanent storage for data used by a program, allowing the information to survive across multiple runs of the application.


2. The Three Essential File Operations (8.3.2)

To safely and successfully interact with a file, a program must perform three steps in sequence:

  1. OPEN the file: This action establishes a connection between the program and the physical file on the storage device. It also tells the computer what mode you intend to use (reading or writing).
  2. PROCESS the data: This involves repeatedly reading data from the file into variables, or writing data from variables into the file.
  3. CLOSE the file: This is vital! Closing the file finalizes the connection, ensures all saved data is correctly written to the disk, and releases the file so other programs can use it.

🚫 Common Mistake: Forgetting to CLOSEFILE can lead to corrupted data or result in data being lost because it was never fully written from the temporary buffer to the permanent storage.


3. File Modes: READ vs. WRITE

When you OPEN a file, you must specify what you want to do. You cannot read and write simultaneously with the single command required by the syllabus.

Mode 1: FOR READ

Purpose: Used when you want to retrieve or load existing data from the file into your program.
Action: The program starts at the beginning of the file and reads data item by item or line by line.

Don't worry if this seems tricky at first! Just remember that when you READ, you are an *extractor*—you are pulling information out.

Mode 2: FOR WRITE

Purpose: Used when you want to save or store new data from your program variables into the file.
Action: This is an aggressive mode!

  • If the file already exists, its contents are completely deleted (overwritten).
  • A new, empty file is created, and your program starts writing data into it.

🚨 Memory Aid: WRITE means WIPE (the old data).


4. The Pseudocode Commands (8.3.2)

We use specific commands in pseudocode for these operations:

1. OPENFILE Command

This command begins the file process and sets the mode.

Syntax: OPENFILE <File Identifier> FOR <File mode>

Example 1 (Reading):
OPENFILE "HighScores.txt" FOR READ

Example 2 (Writing/Overwriting):
OPENFILE "LogData.txt" FOR WRITE

2. READFILE Command

This command moves data from the file into a variable. The file must be opened FOR READ.

Syntax: READFILE <File Identifier>, <Variable>

Example:
READFILE "Names.txt", UserName
// The next available data item in Names.txt is placed into the variable UserName.

3. WRITEFILE Command

This command moves data from a variable into the file. The file must be opened FOR WRITE.

Syntax: WRITEFILE <File Identifier>, <Variable>

Example:
WRITEFILE "LogData.txt", ErrorMessage
// The content of the variable ErrorMessage is written to the LogData.txt file.

4. CLOSEFILE Command

This command releases the file and saves changes permanently.

Syntax: CLOSEFILE <File Identifier>

Example:
CLOSEFILE "HighScores.txt"


5. Reading and Writing Data Items (8.3.2 Guidance)

The syllabus requires you to handle two types of data units:

A. Reading/Writing Single Items of Data

When you store individual pieces of information (like numbers or specific names), you use READFILE or WRITEFILE multiple times. If you are reading data items, you must know their order.

Example of Writing two integers:

DECLARE Score1 : INTEGER
DECLARE Score2 : INTEGER
Score1 ← 88
Score2 ← 91
OPENFILE "Scores.dat" FOR WRITE
WRITEFILE "Scores.dat", Score1
WRITEFILE "Scores.dat", Score2
CLOSEFILE "Scores.dat"

B. Reading/Writing a Line of Text

A "line of text" is often a complete record (a long STRING) that might contain multiple data fields separated by commas (like in a CSV file).

When you read a line of text, the whole string (up to the next carriage return/new line character) is pulled in one go.

Example of Reading a line of text:

DECLARE StudentRecord : STRING
OPENFILE "StudentInfo.csv" FOR READ
READFILE "StudentInfo.csv", StudentRecord
// If the file contained "John Doe, 15, Class A", that entire string is stored in StudentRecord.
CLOSEFILE "StudentInfo.csv"

💡 Key Tip: Iterating through Files
Since files usually contain many lines or items, you almost always use iteration (loops like WHILE or REPEAT UNTIL) to read all the data sequentially. For example, you might use a pre-condition loop (WHILE) combined with a library function (like EOF - End of File) to keep reading until the end of the file is reached, ensuring you capture every record.


Quick Review: File Handling Essentials
  • Purpose: Persistence (saving data permanently).
  • Operations: Open, Process (Read/Write), Close.
  • Read Mode: Pulls data out.
  • Write Mode: Pushes data in, Wipes existing content.