/* A sample program to show the use of fseek and ftell. The program will carry out a binary search on a the master file. Author: Goldine Cupit.*/ #include #define REC_LEN 167 #define KEY_LEN 9 main() { FILE *fp; int first,last,count,mid,recCount; char recordKey[REC_LEN]; // The key at the current file position. char searchKey[] = "000000028"; // Hard coded value of the key value // we are looking for. // The file to be searched is called master. if ((fp = fopen("master","r")) ==NULL) { printf("Problem opening file master\n"); exit(1); } else { // We must determine the number of records in the file. // Use fseek to move the file position to the last byte in the file. fseek(fp,0,SEEK_END); // Use ftell to obtain this byte count. count = ftell(fp); //Compute the number of records in the file recCount = count/REC_LEN; first = 0; last = recCount - 1; //Binary search using the algorithm from A58. //As written, we assume that the search searchKey is in the list. while ( first != last){ mid = (first + last) / 2; //Move the file position to the middle record. fseek(fp, mid*REC_LEN,SEEK_SET); //Read the key field only fscanf(fp,"%9s",recordKey); if (strncmp(searchKey,recordKey,KEY_LEN) <= 0) last = mid; else first = mid + 1; } printf("the index is %d\n",first); } }