file-matching2.c (2196B)
1 /* Exercise 11.10 2 * 3 * NOTE: i suppose that the records stored to the 4 * files are in an ascending order sequence. 5 */ 6 7 #include <stdio.h> 8 #include <stdlib.h> 9 10 #define SIZE 29 11 12 struct record { 13 int account; 14 char name[SIZE]; 15 char address[SIZE]; 16 int phone; 17 double balance; 18 char notes[255]; 19 }; 20 21 int main(void) 22 { 23 FILE *clients, *trans, *newfile; 24 struct record cRec, tRec; 25 int found; 26 27 /* open the clients file */ 28 if( (clients = fopen("oldmast.dat", "r")) == NULL ) { 29 printf("%s: cannot open the file\n", "oldmast.dat"); 30 exit(-1); 31 } 32 33 /* open the transactions file */ 34 if( (trans = fopen("trans.dat", "r")) == NULL ) { 35 printf("%s: cannot open the file\n", "trans.dat"); 36 exit(-1); 37 } 38 39 /* open the new archive file */ 40 if ( (newfile = fopen("newmast.dat", "w")) == NULL ) { 41 printf("%s: cannot open the file\n", "newmast.dat"); 42 exit(-1); 43 } 44 45 /* Read the first record */ 46 fread(&cRec, sizeof(struct record), 1, clients); 47 48 /* loop the clients */ 49 while( !feof(clients) ) { 50 51 fread(&tRec, sizeof(struct record), 1, trans); 52 53 /* check the transactions */ 54 while( !feof(trans) && tRec.account <= cRec.account ) { 55 if(tRec.account == cRec.account) { 56 cRec.balance += tRec.balance; 57 } 58 fread(&tRec, sizeof(struct record), 1, trans); 59 } 60 fwrite(&cRec, sizeof(struct record), 1, newfile); 61 62 rewind(trans); 63 fread(&cRec, sizeof(struct record), 1, clients); 64 } 65 66 fread(&tRec, sizeof(struct record), 1, trans); 67 68 /* check the mismathed transactions */ 69 while( !feof(trans) ) { 70 71 rewind(clients); 72 fread(&cRec, sizeof(struct record), 1, clients); 73 74 found = 0; 75 76 /* loop the clients */ 77 while( !feof(clients) && cRec.account <= tRec.account ) { 78 if(cRec.account == tRec.account) { 79 found = 1; 80 break; 81 } 82 fread(&cRec, sizeof(struct record), 1, clients); 83 } 84 85 if(!found) { 86 printf("Unmatched transaction record for account number %d\n", 87 tRec.account); 88 } 89 90 fread(&tRec, sizeof(struct record), 1, trans); 91 } 92 93 fclose(clients); 94 fclose(trans); 95 fclose(newfile); 96 97 return 0; 98 } /* E0F main */ 99