Solution for Exercise 22-12

ex2212

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

    strcpy(bond.actor,"Sean Connery");
    bond.year = 1962;
    strcpy(bond.title,"Dr. No");

    jbdb = fopen("bond.db","w");
    if(!jbdb)
    {
        puts("SPECTRE wins!");
        exit(1);
    }
    fwrite(&bond,sizeof(struct agent),1,jbdb);
    fclose(jbdb);
    puts("Record written");

    return(0);
}

Output

Record written

Notes

* The fwrite() function at Line 25 uses the & operator to ensure that the address of the bond variable is passed. Also, note that the sizeof operator gets its value from the structure's definition, entry, not from the bond variable. When using sizeof with a structure, use the structure's definition itself, not a structure variable.