Inserting into a file

Files can only be appended. That means that we can only add data to the end of the file. This means to insert a record into a file we need to create a temporary file. The algorithim we will use is -

  1. Open the origonal file and a temporary (new) file.
  2. Copy records up until the point of insertion into the temp file
  3. add the new record to the temp file
  4. Copy the rest of the file into the temp file
  5. delete the origonal file
  6. rename the temp file to match the origonal.

file = OPEN("myFile.txt", R)
temp = OPEN("tempFile.txt", W)

recordInserted = false
WHILE((NOT (reached end of file)) AND recordInserted = false)
    forname = READ(file, 30)
    surname = READ(file, 20)
    age = READ (file, 4)
    if (surnameToAdd < surname)' handles the insert
        WRITE(temp, fornameToAdd)
        WRITE(temp, surnameToAdd)
        WRITE(temp, ageToAdd)

        recordInserted = true
    END IF
    WRITE(temp, forname)
    WRITE(temp, surname)
    WRITE(temp, age)
' Need to insert the record if it happens to be higher than the rest
IF recordInserted = false THEN
    WRITE(temp, fornameToAdd)
    WRITE(temp, surnameToAdd)
    WRITE(temp, ageToAdd)
' write the rest of the file (if any) to the temp file CLOSE(temp)
RENAME("tempFile.txt", "myFile.txt")

The code above has the new record stored in the variables fornameToAdd, surnameToAdd and ageToAdd. You could, with little imagination, see how this could be turned into a procedure called ADDTOSEQUENTIAL. We should be able to then -

ADDTOSEQUENTIAL("bob", "smith", 30)
ADDTOSEQUENTIAL("fred", "flintstone", 22)
ADDTOSEQUENTIAL("zed", "angry", 12)
ADDTOSEQUENTIAL("P", "free", 87)

The abobe would generate a sequential file in the order -

  1. zed angry, 12
  2. fred flintstone, 22
  3. P free, 87
  4. bob smith, 30

NOTE - Actually this code will NOT work for bob! You need a exception case where the origonal file is empty. I left this out to keep things a bit simpler but you should be aware of it. Hopefully you did spot that without my note!