Continuing to build upon our sample program, we take isam2.c and add the ability to scan the index looking for a particular file, and to either update or delete it. The new program is isam3.c. We replace the datadel() function with update().
In the previous examples, if we wanted to delete a record we had to enter an exact match of the key. Sometimes it is desirable to just enter a target and search up or down from that point. In addition, you may not know exactly what keys are in the index, so you can enter something that is close and scan forward or backward until you find the one you want.
If we use GetRecord() as we did before, we can only find a key that exists in the index, as GetRecord() finds only exact matches. Instead, use GetGTERecord(). This finds a key that is equal to the target, but if there is no exact match, it finds the next key after the target. Use TransformKey() to format the key properly. A return of INOT_ERR (160) means the user entered a target that is past all of the keys in the index.
Once we find a starting point we display the data values GetGTERecord() read into the buffer. The user is given the option of updating, deleting, or scanning up or down through the index.
NextRecord and PreviousRecord
As we saw when listing the file sequentially, NextRecord() can find the next record after the one previously found. We can continue to scan forward through the file with NextRecord(), or we can scan backwards through the file with PreviousRecord(). This function works identically to NextRecord() except that it goes the opposite direction through the index.
Once we find the record to update, we can easily change the values and write the record back to the file. We changed the getfld() function so it displays the existing value before asking you for the new value. If you press the Enter/Return key, you get the same value as before.
ReWriteRecord() rewrites the current ISAM record back to the disk. Pass it the number of the data file and a pointer to the buffer where the updated record exists.
In our example, it is possible to change the value of the “item” field, which is our key field. ReWriteRecord() notices the new record has a different value for that key field than the original record. It deletes the old key from the index and adds the new key automatically. This may not be the best practice in a real application, but it serves to illustrate how ReWriteRecord() works. If we have multiple indices based on different fields ReWriteRecord() makes the same change for all key values.
Once we find the record to delete by scanning to it we can easily delete it by using DeleteRecord() as before. Keep in mind that this deletes the Current ISAM Record.