Solution for Exercise 22-12

ex2212

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

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

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

    return(0);
}

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 entry structure itself, entry, not from the bond variable. When using sizeof with a structure, use the structure's definition itself, not a structure variable.