Handling fixed length records

Before reading this make sure you recap fixed length records.

Saving and loading fixed length records is key to understanding how files work. Consider the following record structure -

Name Type Size
Surname Text 30
Name Text 20
age INT 4

We could save a record like this -

file = OPEN("myFLR.data", W)
WRITE(file, "Smith")
WRITE(file, "John")
WRITE(file, 20)
CLOSE(file)

This would lead to the following being saved. You should assume that numbers are saved in 2's complement binary using 32 bits. Mainly becuase they are :) -

"SmithJohn4"

The issue here is that the text is not fixed size. This means we do not know when name should start! I will introduce a procedure called PAD. Given a String it will PAD it out so it always meets the number of bytes specified (or cuts some values off!). So PAD("John", 20) would produce "John                ". Notice the 16 spaces!

file = OPEN("myFLR.data", W)
WRITE(file, PAD("Smith", 30))
WRITE(file, PAD("John",20))
WRITE(file, 20)
CLOSE(file)

Would produce -

"Smith                          John                20"

This may look wasteful, and it is! This is the down side to fixed length records. Adding a second record to it would produce -

file = OPEN("myFLR.data", W)
WRITE(file, PAD("Hamflett", 30))
WRITE(file, PAD("Mr",20))
WRITE(file, 22)
CLOSE(file)

"Smith                          John                20Hamlett                       Mr                  22"

Next reading FLR >>