/* C: The Complete Reference, 4th Ed.

(Paperback) by Herbert Schildt ISBN: 0072121246 Publisher: McGraw-Hill Osborne Media; 4 edition (April 26, 2000) */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define NUM_ELEMENTS 4 /* This is an arbitrary number that should be determined dynamically for each list. */ struct address { char name[30]; char street[40]; char city[20]; char state[3]; char zip[11]; } ainfo; struct address addrs[NUM_ELEMENTS] = { "A. Alexander", "101 1st St", "Olney", "Ga", "55555", "B. Bertrand", "22 2nd Ave", "Oakland", "Pa", "34232", "C. Carlisle", "33 3rd Blvd", "Ava", "Or", "92000", "D. Dodger", "4 Fourth Dr", "Fresno", "Mi", "45678" }; void void void char quick_disk(FILE *fp, int count); qs_disk(FILE *fp, int left, int right); swap_all_fields(FILE *fp, long i, long j); *get_zip(FILE *fp, long rec);

int main(void) { FILE *fp; /* first, create a file to sort */ if((fp=fopen("mlist", "wb"))==NULL) { printf("Cannot open file for write.\n"); exit(1); } printf("Writing unsorted data to disk.\n"); fwrite(addrs, sizeof(addrs), 1, fp); fclose(fp); /* now, sort the file */ if((fp=fopen("mlist", "rb+"))==NULL) { printf("Cannot open file for read/write.\n"); exit(1); } printf("Sorting disk file.\n"); quick_disk(fp, NUM_ELEMENTS); fclose(fp); printf("List sorted.\n"); return 0;

x) < 0) && (i < right)) i++. sizeof(ainfo). int count) { qs_disk(fp.j). p = &ainfo. fp). . /* first read in record i and j */ fseek(fp. rec*sizeof(ainfo). count-1). b[sizeof(ainfo)]. } /* Return a pointer to the zip code */ char *get_zip(FILE *fp. SEEK_SET). /* then write them back in opposite slots */ fseek(fp. fp). right). sizeof(ainfo)*j. long j) { char a[sizeof(ainfo)]. 1. sizeof(ainfo). 1. j. 0. fseek(fp. } void swap_all_fields(FILE *fp. fp). sizeof(ainfo)*j. int right) { long int i. } } while(i <= j). /* get the middle zip */ do { while((strcmp(get_zip(fp. 1. fread(a. sizeof(ainfo)*i. j). fwrite(b. SEEK_SET).i).x) > 0) && (j > left)) j--. long rec) { struct address *p. SEEK_SET). strcpy(x. if(i < right) qs_disk(fp. i++. 1. SEEK_SET). sizeof(ainfo). return ainfo. fwrite(a. if(left < j) qs_disk(fp.zip. */ void quick_disk(FILE *fp. j--. while((strcmp(get_zip(fp. fseek(fp. i = left. char x[100]. i. int left. get_zip(fp. if(i <= j) { swap_all_fields(fp. left. } void qs_disk(FILE *fp. (long)(i+j)/2)). sizeof(ainfo). (int) j). SEEK_SET). long i. fread(p. fread(b.} /* A Quicksort for files. sizeof(ainfo)*i. j = right. fp). fseek(fp. fp). sizeof(ainfo). (int) i. 1.

} .

Sign up to vote on this title
UsefulNot useful