CustIndex[nRecord].Customer = ftell(DataFile); strcpy(CustIndex[nRecord].szName, Customer->szName);
After the index has been set up, the program writes the record to the database and closes the file:
fwrite(Customer, sizeof(CUSTNAME), 1, DataFile);
fclose(DataFile);
When the user requests a record, the program searches for the record using both a linear search and the bsearch() function. I used both search techniques in Listing 10.5 simply to show how they are implemented; your program should use one or the other (probably bsearch() because it is easy to implement and fast).
To use a binary search, the index must be sorted. When the user wants the names displayed, the program sorts the index list. The programmer can choose to sort the index either as names are added (which slows the process of adding names) or when the sorted index list is used. This program would have been better if it included a flag to indicate when the list was already sorted.
The following code shows how a record is retrieved and displayed:
case ‘D’: /* Display a record */ case ‘d’:
printf(“Display customer (total %d).\n”, nRecord + 1);
qsort(CustIndex, nRecord + 1, sizeof(CUSTINDEX), compare);
for (i = 0; nDebug && i <= nRecord; i++)
{/* In debug mode, display the sorted index list. */ printf(“Record %2d szName ‘%s’\n”,
i,
CustIndex[i].szName);
}
In the debug mode, the program first shows the programmer the index list. This display is useful when you want to see the results of the sort.