training

Code I wrote during training
git clone git://git.bitsmanent.org/training
Log | Files | Refs | README

fig11_07_mod.c (1179B)


      1 /* Exercise 11.9 */
      2 
      3 /* Fig. 11.7: fig11_07.c
      4    Reading and printing a sequential file */
      5 #include <stdio.h>
      6 
      7 #define SIZE 29
      8 
      9 struct record {
     10    int account;
     11    char name[SIZE];
     12    char address[SIZE];
     13    int phone;
     14    double balance;
     15    char notes[255];
     16 };
     17 
     18 int main(int argc, char *argv[])
     19 { 
     20    FILE *cfPtr;
     21    struct record recPtr;
     22 
     23    if(argc != 2) {
     24       printf("Usage: %s <file>\n", argv[0]);
     25       return -1;
     26    }
     27 
     28    /* fopen opens file; exits program if file cannot be opened */ 
     29    if ( ( cfPtr = fopen( argv[1], "r" ) ) == NULL ) {
     30       printf( "File could not be opened\n" );
     31    } /* end if */
     32    else { /* read account, name and balance from file */
     33       printf( "%-10s%-13s%s\n", "Account", "Name", "Balance" );
     34       fread(&recPtr, sizeof(struct record), 1, cfPtr);
     35 
     36       /* while not end of file */
     37       while ( !feof( cfPtr ) ) { 
     38          printf( "%-10d%-13s%7.2f\n",
     39             recPtr.account, recPtr.name, recPtr.balance );
     40          fread(&recPtr, sizeof(struct record), 1, cfPtr);
     41       } /* end while */
     42 
     43       fclose( cfPtr ); /* fclose closes the file */
     44    } /* end else */
     45 
     46    return 0; /* indicates successful termination */
     47 
     48 } /* end main */
     49