Solution for Exercise 22-16

ex2216

#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);
    }
    fseek(a007,sizeof(struct entry)*1,SEEK_SET);
    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

* Sample output (assuming that the bond.db file exists, and was created according to the book):

* If you want to explore the fseek() function further, modify Exercise 22-13 so that additional records are written to the bond.db file. Then modify this Exercise so that a specific record is plucked from that file.

* The *1 in Line 21 is a personal preference. As with Exercise 20-1, I'm using the *1 to be consistent with other code I write. That *1 confirms to me that the fseek() function is moving by an increment of 1. Feel free to omit the *1 in your own code