10.1 What a Random File Is — Direct Access
There are three ways a file can be organised. Understanding the difference is essential before the code makes sense.
| Type | Order | Access | Example |
|---|---|---|---|
| Serial | Arrival order (no sorting) | Sequential — read from start | Receipts in a box |
| Sequential | Sorted by key field | Sequential — read in order | Paper dictionary |
| Random | Fixed-length records | Direct — jump to any record | Library database |
- A random file = fixed-length records + direct access.
- Because every record is the same size, the program can calculate exactly where record N begins.
- It can then jump straight there using
SEEK— that jump is direct access.
- A random file allows direct access — any record can be reached by its position.
- A single book can be read or updated without reading the records before it.
- Access is therefore much faster for a large file.
- Both store records one after another
- The difference is about order
- Serial = no sorting; Sequential = sorted by key field
- Direct access = jump straight to the record
- Only one file type supports this
- Think: which type allows SEEK?
What a Random File Is
10.2 The Record Type & The Five Commands
First you describe the shape of one record using a user-defined TYPE. This is the blueprint — it does not store data yet, it just says what fields a record has and what type each field is.
TYPE Book
DECLARE Title : STRING
DECLARE Author : STRING
DECLARE YearPublished : INTEGER
DECLARE ISBN : STRING
DECLARE CopiesAvailable : INTEGER
ENDTYPEThen you use the five file commands:
| Command | Purpose |
|---|---|
OPENFILE "file" FOR RANDOM | Opens the file for direct access |
SEEK "file", position | Moves the pointer to a record position |
GETRECORD "file", variable | Reads the record at the pointer into a variable |
PUTRECORD "file", variable | Writes the variable to the pointer position |
CLOSEFILE "file" | Closes the file and saves changes |
SEEKpositions the pointer;GETRECORDreads from that slot andPUTRECORDwrites into it.- SEEK must always come before GETRECORD or PUTRECORD.
- Use TYPE...ENDTYPE wrapper
- Three DECLARE lines with correct names
- Correct data types: INTEGER, STRING, BOOLEAN
- Same shape as Member: TYPE, three DECLARE lines, ENDTYPE
- Pick the right type for a date
Record Types & The Five Commands
10.3 Adding a Record — PUTRECORD
Adding follows three steps: build the record in a variable, SEEK to where it should go, then PUTRECORD to write it. There is no read involved — you are writing fresh data in.
DECLARE NewBook : Book
// 1. Build the record in a variable
NewBook.Title <- "Pride and Prejudice"
NewBook.Author <- "Jane Austen"
NewBook.YearPublished <- 1813
NewBook.ISBN <- "9780141199078"
NewBook.CopiesAvailable <- 12
// 2. Open, SEEK to position, PUTRECORD
OPENFILE "LibraryDatabase.dat" FOR RANDOM
SEEK "LibraryDatabase.dat", 5
PUTRECORD "LibraryDatabase.dat", NewBook
CLOSEFILE "LibraryDatabase.dat"- Assign every field of NewBook
- OPENFILE FOR RANDOM
- SEEK to position 9, then PUTRECORD
- CLOSEFILE
- Same three steps — the variable is of type Member
- Assign all three fields
- SEEK to position 4, PUTRECORD, CLOSEFILE
- OPENFILE, SEEK to 0, PUTRECORD, CLOSEFILE
- Only 4 lines needed
- Same four lines, change the file and position
- Assign every field of the record before writing it.
- Examiners check that each field of the user-defined type is set before PUTRECORD.
- Unassigned fields may contain garbage.
Adding a Record (PUTRECORD)
10.4 Reading & Updating a Record
The update cycle: read the slot, change a field in the variable, then write the variable back to the same slot.
DECLARE ExistingBook : Book
OPENFILE "LibraryDatabase.dat" FOR RANDOM
// read the record at position 5
SEEK "LibraryDatabase.dat", 5
GETRECORD "LibraryDatabase.dat", ExistingBook
// change one field
ExistingBook.CopiesAvailable <- 20
// write it back to the SAME slot
SEEK "LibraryDatabase.dat", 5
PUTRECORD "LibraryDatabase.dat", ExistingBook
CLOSEFILE "LibraryDatabase.dat"- SEEK 3, GETRECORD into B
- B.CopiesAvailable = B.CopiesAvailable + 1
- SEEK 3 again, PUTRECORD B
- CLOSEFILE
- Read, change the one field (Active)
- SEEK back to 8, write
- No write needed — just SEEK, GETRECORD, OUTPUT
- Output B.Title
- SEEK 7, GETRECORD into M
- OUTPUT M.Name
- No PUTRECORD needed
Reading & Updating a Record
10.5 Shifting Records to Make Space
To insert a record in the middle of a file, you must first shift all records after that position one slot forward. Start from the last record and work backward to avoid overwriting records you have not moved yet.
DECLARE Pupil : Student
DECLARE Position : INTEGER
OPENFILE "StudentFile.dat" FOR RANDOM
// move records from 20 down to 10, backward, into the next slot
FOR Position <- 20 TO 10 STEP -1
SEEK "StudentFile.dat", Position
GETRECORD "StudentFile.dat", Pupil
SEEK "StudentFile.dat", Position + 1
PUTRECORD "StudentFile.dat", Pupil
NEXT Position
CLOSEFILE "StudentFile.dat"- Always shift from the last record backward (STEP -1).
- If you shift forward, you overwrite the next record before you have read it — destroying data.
- Loop from 12 TO 8 STEP -1 (backward)
- SEEK position, GETRECORD, SEEK position+1, PUTRECORD
- Work backward to avoid overwriting
- Same pattern — loop 15 TO 5 STEP -1
- Read from Position, write to Position + 1
10.6 Searching a Random File
To search for a record by name (or any field), loop through positions with SEEK + GETRECORD, compare each record's field, and stop when found. Use a Boolean flag.
DECLARE Customer : Member
DECLARE Position : INTEGER
DECLARE Found : BOOLEAN
DECLARE SearchName : STRING
OUTPUT "Enter the member's name"
INPUT SearchName
Found <- FALSE
Position <- 0
OPENFILE "Members.dat" FOR RANDOM
WHILE Found = FALSE AND Position < 1000 DO
SEEK "Members.dat", Position
GETRECORD "Members.dat", Customer
IF Customer.Name = SearchName THEN
Found <- TRUE
ELSE
Position <- Position + 1
ENDIF
ENDWHILE
CLOSEFILE "Members.dat"
IF Found THEN
OUTPUT "Found at position", Position
ELSE
OUTPUT "Not found"
ENDIF- The search uses a
WHILEloop with two conditions:Found = FALSEANDPosition < maxRecords. - This stops either when the record is found or when all records have been checked.
10.7 Python — Serialising with pickle
Python does not have Cambridge pseudocode's PUTRECORD / GETRECORD. Instead, the pickle module lets you serialise any Python object (class instance, dictionary, list) to a binary file and read it back.
import pickle
class Book:
def __init__(self, title, author, year, isbn, copies):
self.title = title
self.author = author
self.year = year
self.isbn = isbn
self.copies = copies
def __str__(self):
return f"{self.title} by {self.author} ({self.copies} copies)"
book = Book("To Kill a Mockingbird", "Harper Lee", 1960,
"9780060935467", 5)
# Write (like PUTRECORD)
with open("book.dat", "wb") as f:
pickle.dump(book, f)
# Read back (like GETRECORD)
with open("book.dat", "rb") as f:
loaded = pickle.load(f)
print(loaded) # To Kill a Mockingbird by Harper Lee (5 copies)pickle.dump(obj, file)= PUTRECORD (write object).pickle.load(file)= GETRECORD (read object).- The file mode is
"wb"for writing binary,"rb"for reading binary.
- Import pickle
- open("member.dat", "wb") + pickle.dump()
- open("member.dat", "rb") + pickle.load()
- Print the loaded dictionary
- Same pattern — dump the list, load it back
- Loop through the loaded list to print each title
10.8 Python — Direct Access with seek
To replicate Cambridge pseudocode's SEEK + fixed record size in Python, use file.seek(position * RECORD_SIZE) to jump to a record, then pickle.dump() / pickle.load() to read or write.
import pickle
RECORD_SIZE = 128 # every record reserves a fixed block
def put_record(filename, position, record):
with open(filename, "r+b") as f:
f.seek(position * RECORD_SIZE) # like SEEK
pickle.dump(record, f) # like PUTRECORD
def get_record(filename, position):
with open(filename, "rb") as f:
f.seek(position * RECORD_SIZE) # like SEEK
return pickle.load(f) # like GETRECORD- The byte offset for record N is
N * RECORD_SIZE. - For record 6 with size 200:
seek(6 * 200)=seek(1200). - This is the Python equivalent of
SEEK "file", 6.
- Offset = 2 * 128 = 256
- Open in "r+b" mode (read+write binary)
- f.seek(2 * 128) then pickle.dump(b, f)
- Offset = 5 * 128 = 640
- Open in "rb" mode (read binary)
- f.seek(5 * 128) then b = pickle.load(f)
Shifting, Searching & Python (pickle/seek)
10.9 Full Exam-Style Question
A driving school stores lesson records in a random file Lessons.dat. Each record is of type TLesson:
TYPE TLesson
DECLARE LessonID : INTEGER
DECLARE StudentName : STRING
DECLARE Instructor : STRING
DECLARE Booked : BOOLEAN
ENDTYPENewLesson of type TLesson has been filled. Write pseudocode to write NewLesson to position 10 of Lessons.dat.- (i) SEEK to position 10
- (ii) PUTRECORD to write NewLesson
- (iii) CLOSEFILE Lessons.dat
- Write a pseudocode procedure
FindStudent(Target : STRING)that searchesLessons.datfor a lesson whereStudentNameequalsTargetandBookedis TRUE. - Output the lesson ID and instructor if found, or "Not found".
- The file has 500 records.
- Declare Lesson, Index, Found
- Found = FALSE, Index = 0
- WHILE Index < 500 AND Found = FALSE
- SEEK, GETRECORD, check StudentName AND Booked
- If match: output and set Found = TRUE
- Else Index = Index + 1
- After loop: if not found, output "Not found"
Slot from Lessons.dat using RECORD_SIZE = 96 and pickle.- RECORD_SIZE = 96
- Open in "rb" mode
- f.seek(Slot * RECORD_SIZE)
- lesson = pickle.load(f)
✓ Key Points Summary
10.10 Practice Tasks
Fifteen exam-style random file tasks. Each shows only the question — click Hint for the thought process, or Help for the worked solution.
- For every random file task, the marker checks: (1) correct OPENFILE FOR RANDOM, (2) SEEK before GETRECORD/PUTRECORD, (3) all fields assigned before PUTRECORD, (4) CLOSEFILE at the end.
- The most common mark loss is forgetting SEEK before GETRECORD/PUTRECORD.
Question Bank
Answer all questions, then press Submit Quiz to see your score.
Question 1Multiple Choice
What is the key feature of a random file?
Question 2True / False
In a random file, you must read records 0-7999 before reading record 8000.
Question 3Multiple Choice
Which pseudocode keyword defines a record type?
Question 4Multiple Choice
Which command positions the file pointer at a specific record?
Question 5True / False
PUTRECORD replaces whatever was previously at the target position.
Question 6Multiple Choice
What are the steps to update a record?
Question 7Multiple Choice
In Python, which module serialises objects to a binary file?
Question 8True / False
In Python, file.seek(N * RECORD_SIZE) positions the pointer at record N.
Question 9Multiple Choice
When shifting records to make space, you should start from:
Question 10Multiple Choice
Which is the correct pseudocode to read the record at position 3?
Question 11True / False
A serial file stores records in the order they arrive, with no sorting.
Question 12Multiple Choice
What file mode is used to open a random file in Cambridge pseudocode?
Answer all 12 questions to enable submission.