Searching in a file
When searching a serial file you will need to perform a serial search. We have already seen how a record can be READ() and WRITE() and we already know how a record is stored in a file. To perform the serial search we will need to -
- Open the file
- Read in a record.
- Compare the record with the search term
- Either move to the next record or stop (if record is found or at the end of the file)
- report success or failure
A search will normally occur on the key. But also it could occur on any field of the record or even multiple fields. For example let us assume we are looking for "Fred Flintstone" in a serial file. This is split up into forname and surname. So we could use the following algorithim (assuming just surname, forname and age are the only things stored).
file = OPEN("myFile.txt", R)
recordFound = false
WHILE(not (reached end of file) AND recordFound = false)
forname = READ(file, 30)
surname = READ(file, 20)
age = READ (file, 4) ' note that we must read in the age to advance
if (forname = "fred" AND surname = "flintstone") recordFound = true
END WHILE
The main points to bare in mind when searching through a serial file are -
- There is no order to the records so ALL must be considered.
- You will need to read the WHOLE record in first and then compare it (even if you are not interested in all of the values)
- You need to use a while loop which will test if the last record has been reached (or the end of the file). Technially this is either done through a special return value or using the built in counter and testing it is less than length.