Solution for Exercise 22-14

ex2214

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

int main()
{
    struct entry {
        char actor[32];
        int year;
        char title[32];
    };
    struct entry bond;
    FILE *a007;

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

    return(0);
}

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 entry. 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, then it's because of problems like this.