/* ******************************************************* * Author: Nikitas N. Karanikolas, Assistant Professor * * Creation Date: February 21, 2009 * ******************************************************* */ #include #include "types.h" int partial_sort(FILE *fp1, FILE *fp2) { personnel_rec e1, e2; int howmany; int sorted=1; /* sorted <- true */ howmany=fread(&e1,sizeof(personnel_rec),1,fp1); if (howmany<1) return sorted; do { howmany=fread(&e2,sizeof(personnel_rec),1,fp1); if (howmany<1) { fwrite(&e1,sizeof(personnel_rec),1,fp2); break; } if (strcmp(e1.key,e2.key)<=0) { fwrite(&e1,sizeof(personnel_rec),1,fp2); memcpy(&e1,&e2,sizeof(personnel_rec)); } else { fwrite(&e2,sizeof(personnel_rec),1,fp2); sorted=0; /* sorted <- false */ } } while (1); return sorted; } main (int argc, char *argv[]) { int i=0; int sorted; FILE *fp1, *fp2; if (argc<2) { printf("You should provide the name of the file to be created."); exit(1); } do { if (i % 2 == 0) { fp1=fopen(argv[1],"rb"); fp2=fopen("tmp$$.tmp","wb"); } else { fp1=fopen("tmp$$.tmp","rb"); fp2=fopen(argv[1],"wb"); } sorted=partial_sort(fp1,fp2); fclose(fp1); fclose(fp2); i++; } while (!sorted); printf("\nNumber of file traverses: %d\n", i); if (i % 2 == 1) { unlink(argv[1]); /* delete the original file */ rename("tmp$$.tmp",argv[1]); /* rename the temporary file to the original */ } else { unlink("tmp$$.tmp"); /* delete temporary file */ } }