A Level · Topic 20.2
A-Level Computer Science 9618 / Topic 20 / A2

Records that last.

Data in variables disappears when a program ends; data in a file does not. Learn how to open files in READ, WRITE, APPEND and RANDOM mode, read and write records, add a record to a serial file and insert one into a sequential file, and use SEEK, GETRECORD and PUTRECORD to go straight to a record in a random file.

The key idea

A file must be opened in a mode before use and closed afterwards. READ reads lines from the start; WRITE creates a new file (any existing data is lost); APPEND adds to the end; RANDOM opens a file of fixed-length records for direct access. In a serial file records are stored in the order they were added; in a sequential file they are stored in order of a key field, so inserting a record means copying to a new file. In a random file each record is at an address, often calculated from its key by a hashing function, and SEEK moves the file pointer straight there so GETRECORD and PUTRECORD can read or replace that record.

Serial, sequential and random (direct access) files Serial Sequential Random M031M007M052M012M040 M007M012M031M040M052 01234 records in the order they were added; new records go at the end records stored in order of a key field; inserting means rewriting fixed-length records at numbered slots SEEK file, 3
Fig. 1: the same five member records stored serially, sequentially by ID, and at numbered addresses in a random file
Section 01

Text files and file modes.

A text file is a series of lines read and written one after another as strings. A record can be stored as one line, with the fields in fixed positions. Run the file programs in the lab to see lines being written and read back.

StatementEffect
OPENFILE "Members.txt" FOR READopens the file so lines can be read from the start
OPENFILE "Members.txt" FOR WRITEcreates a new file; any data already in a file of that name is lost
OPENFILE "Members.txt" FOR APPENDopens the file so new lines are added after the existing data
READFILE "Members.txt", LineOfTextreads the next line into a STRING variable
WRITEFILE "Members.txt", LineOfTextwrites the data as a new line (WRITE or APPEND mode)
EOF("Members.txt")TRUE when there are no more lines to read
CLOSEFILE "Members.txt"closes the file when it is no longer needed

Each line of Members.txt holds a 4-character member ID followed by a name, for example M007Lee. This function searches the file for an ID and returns the name, or an empty string if it is not there:

FUNCTION FindMember(SearchID : STRING) RETURNS STRING
    DECLARE LineOfText : STRING
    DECLARE Found : STRING
    Found ← ""
    OPENFILE "Members.txt" FOR READ
    WHILE NOT EOF("Members.txt") AND Found = ""
        READFILE "Members.txt", LineOfText
        IF MID(LineOfText, 1, 4) = SearchID THEN
            Found ← MID(LineOfText, 5, LENGTH(LineOfText) - 4)
        ENDIF
    ENDWHILE
    CLOSEFILE "Members.txt"
    RETURN Found
ENDFUNCTION
Your turn
Write pseudocode to add the record for a new member with ID M060 and name Diaz to the end of Members.txt without losing the existing records.
Examiner trap

Use WHILE NOT EOF(...) before each READFILE, not a FOR loop with a guessed number of lines. EOF is also TRUE straight away for an empty file, so the loop correctly runs zero times.

Section 02

Serial and sequential files.

Both kinds are read from the beginning, one record after another. The difference is the order the records are stored in, and that changes how records are added and found.

Serial fileSequential file
Order of recordsthe order they were added (chronological)sorted by a key field, e.g. member ID
Adding a recordappend it to the endcopy records to a new file, writing the new record in its correct place
Searchingread every record until found or the end of the filecan stop as soon as a key greater than the one wanted is read
Typical usea log of transactions as they happena master file processed in key order in a batch (e.g. payroll)

To insert NewLine into the sequential file Members.txt, every record is copied to NewMembers.txt and the new record is written just before the first record with a larger key:

DECLARE LineOfText : STRING
DECLARE NewLine : STRING
DECLARE Inserted : BOOLEAN
NewLine ← "M020Patel"
Inserted ← FALSE
OPENFILE "Members.txt" FOR READ
OPENFILE "NewMembers.txt" FOR WRITE
WHILE NOT EOF("Members.txt")
    READFILE "Members.txt", LineOfText
    IF Inserted = FALSE AND MID(LineOfText, 1, 4) > MID(NewLine, 1, 4) THEN
        WRITEFILE "NewMembers.txt", NewLine
        Inserted ← TRUE
    ENDIF
    WRITEFILE "NewMembers.txt", LineOfText
ENDWHILE
IF Inserted = FALSE THEN
    WRITEFILE "NewMembers.txt", NewLine
ENDIF
CLOSEFILE "Members.txt"
CLOSEFILE "NewMembers.txt"
Worked example Trace the insertion
Members.txt holds M007Lee, M012Shah, M031Novak, M040Ito and M052Grant, in that order. Trace the code above and give the contents of NewMembers.txt.
  1. M007Lee: is "M007" > "M020"? No. Write M007Lee.
  2. M012Shah: "M012" > "M020"? No. Write M012Shah.
  3. M031Novak: "M031" > "M020"? Yes, and Inserted is FALSE, so write M020Patel, set Inserted to TRUE, then write M031Novak.
  4. M040Ito and M052Grant: Inserted is TRUE, so each is simply copied.
  5. End of file: Inserted is TRUE, so the final IF does nothing.
Answer: M007Lee, M012Shah, M020Patel, M031Novak, M040Ito, M052Grant. The final IF is needed for a new key larger than every existing key, which must be written at the end.
Examiner trap

You cannot insert a line into the middle of a text file in place. For a sequential file the answer must copy the records to a new file (and then, usually, the new file replaces the old one).

Stage 1 · Learn

Check what the sim just showed you

Four quick checks. Each correct answer earns XP and records this skill on your profile.

Quick check+10 XP

Which file mode creates a new file, losing any data already in a file of that name?

Quick check+10 XP

In a sequential file, how are the records stored?

Quick check+10 XP

In the lab, what must happen before a program can read lines from a file it has just written?

Quick check+10 XP

Which command reads the record at the file pointer of a random file?

Section 03

Random (direct access) files.

A random file stores fixed-length records, usually of a user-defined record type. Because every record is the same length, the record at any address can be reached directly without reading the ones before it.

TYPE StockItem
    DECLARE ItemCode : INTEGER
    DECLARE Description : STRING
    DECLARE Quantity : INTEGER
ENDTYPE

DECLARE Item : StockItem
DECLARE Address : INTEGER
Address ← 1047 MOD 500     // hashing function: address 47
OPENFILE "Stock.dat" FOR RANDOM
SEEK "Stock.dat", Address
GETRECORD "Stock.dat", Item
Item.Quantity ← Item.Quantity - 3
SEEK "Stock.dat", Address
PUTRECORD "Stock.dat", Item
CLOSEFILE "Stock.dat"
Worked example Shift records to make space
Records are stored at addresses 1 to 6 of the random file Queue.dat. Write pseudocode to move every record one place later (to addresses 2 to 7) so that a new record NewEntry can be written at address 1.
  1. Work from the END backwards, otherwise record 1 would overwrite record 2 before record 2 had been moved.
  2. OPENFILE "Queue.dat" FOR RANDOM, then FOR Position ← 6 TO 1 STEP -1.
  3. Inside the loop: SEEK "Queue.dat", Position, GETRECORD "Queue.dat", Entry, SEEK "Queue.dat", Position + 1, PUTRECORD "Queue.dat", Entry, then NEXT Position.
  4. After the loop: SEEK "Queue.dat", 1, PUTRECORD "Queue.dat", NewEntry, CLOSEFILE "Queue.dat".
Answer: A count-down loop with STEP -1 that SEEKs, GETRECORDs, SEEKs one place on and PUTRECORDs, followed by writing NewEntry at address 1.
Your turn
Using the hashing function ItemCode MOD 500, at which address is item 2318 stored? Which other item code from 2300 to 2999 would collide with it?
Examiner trap

Always SEEK before PUTRECORD when updating a record you have just read. Re-seeking the same address makes certain the changed record replaces the original rather than being written somewhere else.

Stage 2 · Exam

Exam-style questions

Unlocks once the four checks above are done. Worth more XP, written to A Level Paper 3 and Paper 4 standard.

Finish the four checks above to unlock the exam questions
Exam style+20 XP

Records are stored at addresses given by Key MOD 100. Which key collides with key 4271?

Exam style+20 XP

Why must a new record be inserted into a sequential text file by copying to a new file?

Exam style+20 XP

A file of daily sales transactions is added to as each sale happens. Which organisation is most suitable?

Exam style+20 XP

What does EOF("Data.txt") return when Data.txt is an empty file opened for READ?

Skill unlocked

Serial, sequential and random files, processed.

This skill is now recorded on your profile. Keep the chain going.

-Rank -Level -Score -Topics
Go deeper · practice
Six original Cambridge-style questions
File modes, reading and writing records, serial and sequential files, and random files with SEEK, GETRECORD and PUTRECORD.