Solution for Exercise 22-16

ex2216

#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;

    jbdb = fopen("bond.db","r");
    if(!jbdb)
    {
        puts("SPECTRE wins!");
        exit(1);
    }
    /* locate the 2nd record based on the
       size of structure agent */
    fseek(jbdb,sizeof(struct agent)*1,SEEK_SET);
    fread(&bond,sizeof(struct agent),1,jbdb);
    printf("%s\t%d\t%s\n",
            bond.actor,
            bond.year,
            bond.title);
    fclose(jbdb);

    return(0);
}

Output

Roger Moore      1973    Live and Let Die

Notes

* The sample output assumes 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 to pluck a specific record from that file.

* The *1 in Line 23 is a personal preference. As with Exercise 20-1, I use the *1 to be consistent with other code I write. The *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.