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 -

  1. Open the file
  2. Read in a record.
  3. Compare the record with the search term
  4. Either move to the next record or stop (if record is found or at the end of the file)
  5. 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 -