20.2 File Processing and Exception Handling

2026 Syllabus Objectives

By the end of this subtopic, you should be able to:

  • write code to perform file-processing operations
  • open a file in read, write, and append mode, and close a file
  • read a record from a file and write a record to a file
  • perform file-processing operations on serial, sequential, and random files
  • show understanding of what an exception is
  • explain the importance of exception handling
  • know when it is appropriate to use exception handling
  • write program code to use exception handling

File processing

File processing means working with files that are stored on secondary storage, such as a hard drive or SSD. A program may need to store data in a file so that the data is kept even after the program ends. It may also need to read data back later.

A file can store many pieces of related data. These are often stored as records. A record is a group of fields that belong together. For example, a student record might contain a name, address, and class name.

Example of a record structure:

TYPE StudentRecord
    DECLARE name : STRING
    DECLARE address : STRING
    DECLARE className : STRING
ENDTYPE

In file processing, a program usually does four main jobs. It opens the file, reads from it or writes to it, and then closes it. Closing the file is important because it finishes the file operation properly and helps prevent data loss.


Opening and closing files

Before a program can use a file, it must open it. When a file is opened, the program chooses a mode. The mode tells the computer what the program wants to do with the file.

The three file modes you must know are:

  • Read mode: used when the program wants to get data from the file
  • Write mode: used when the program wants to put data into the file and replace any old contents
  • Append mode: used when the program wants to add new data to the end of the file

After the program has finished with the file, it should close it. Closing a file ends access to the file and makes sure the data has been properly saved.

Basic pseudocode:

OPEN filename FOR READ
READ record FROM filename
CLOSE filename
OPEN filename FOR WRITE
WRITE record TO filename
CLOSE filename
OPEN filename FOR APPEND
WRITE record TO filename
CLOSE filename

What each mode does

Read mode is used when data already exists in the file and the program only needs to look at it or copy it into memory.

Write mode is used when the program wants to create new file contents. If the file already has data in it, that old data is overwritten. This means it is replaced.

Append mode is used when old data must be kept and new data should be added after it. This is useful for files such as logs, where each new event is added to the end.

Sign in to view full notes