We have already seen that data can be stored in a text file for permanent storage review of AS file handling
We can OPEN, CLOSE, READ, WRITE and APPEND to files eg:
Can you imagine what this program is doing?
DECLARE line : STRING
DECLARE lineNum : INTEGER
OPENFILE "costData.txt" FOR WRITE
lineNum ← 0
OUTPUT "Enter new cost data or 0 to quit"
INPUT data
WHILE data <> 0 DO
line ← lineNum&". "&data
WRITEFILE "costData.txt", line
lineNum ← lineNum + 1
INPUT data
END WHILE
CLOSEFILE "costData.txt"
Note that WRITEFILE and READFILEprocess individual STRINGS.
As you can see, records of data are entered into the file one after the other in no particular order. This is an example of a serial file.
If we were to put records of data one after the other in a particular order, this would be an example of a sequential file.
If we could store data at a particular location/address in the file without simply storing it at the next location, this would be an example of a random file. Hashing concepts are useful here.
In pseudocode we can imagine the concept of not simply reading and writing text to a file, but reading and writing entire records to a file!
For example:
TYPE Car
regNo : STRING
mileage : INTEGER
END TYPE
DECLARE c : Car
INPUT c.regNo
INPUT c.mileage
OPENFILE "carData.txt" FOR RANDOM
SEEK "carData.txt",1 #this will take the file pointer to the start of the file
PUTRECORD "carData.txt", c
CLOSEFILE "carData.txt"
We can put records of data into a random file by using hashing algorithms. Random refers to the idea that the data is not stored serially. A memory location has to be generated somehow. Hash functions are perfect for this eg:
DECLARE address : INTEGER
TYPE Car
regNo : STRING
mileage : INTEGER
END TYPE
DECLARE c : Car
INPUT c.regNo
INPUT c.mileage
OPENFILE "carData.txt" FOR RANDOM
//call a hash function to generate an address in the file
address ← hash(c.regNo)
//now use SEEK to get to the correct location on the file
SEEK "carData.txt", address
//now write the record to the file
PUTRECORD "carData.txt", c
CLOSEFILE "carData.txt"
Notice that the PSEUDOCODE for PUTRECORD has no idea where it is putting the record. It simply puts it where the file pointer is pointing. So, we need to use SEEK to ensure that the file pointer is at the correct address.
We can use GETRECORD using a similar approach. Let's say a file stores Car records.
DECLARE address : INTEGER
DECLARE searchReg : INTEGER
DECLARE result : Car
OUTPUT "Enter the car registration you are searching for:"
INPUT searchReg
OPENFILE "carData.txt" FOR RANDOM
//call a hash function to generate an address in the file
address ← hash(searchReg)
//now use SEEK to get to the correct location on the file
SEEK "carData.txt", address
//now write the record to the file
GETRECORD "carData.txt", result
CLOSEFILE "carData.txt"
OUTPUT result.regNo & ", "& result.mileage