Solution for Exercise 22-14

ex2214

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    struct agent {
        char actor[32];
        int year;
        char title[32];
    };
    struct agent bond;
    FILE *jbdb;
    int r;

    jbdb = fopen("bond.db","r");
    if(!jbdb)
    {
        puts("SPECTRE wins!");
        exit(1);
    }
    while( !feof(jbdb) )
    {
        r = fread(&bond,sizeof(struct agent),1,jbdb);
        if( r==0 )
            break;
        printf("%s\t%d\t%s\n",
                bond.actor,
                bond.year,
                bond.title);
    }
    fclose(jbdb);

    return(0);
}

Output

Sean Connery    1962    Dr. No
Roger Moore     1973    Live and Let Die
Pierce Brosnan  1995    GoldenEye

Notes

* Always ensure that you use the size of the structure itself, not the structure variable, when reading structures from disk in random file access! In this listing, the structure is name agent. The variable is bond. Many beginners write the fread() function at Line 21 as:

This format is incorrect! The size is based on the structure, not the variable. That's because the variable could be smaller than the overall size of the structure. If you ever have problems reading and writing random access files, it's due to problems like this.