Solution for Exercise 22-13

ex2213

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

int main()
{
    struct agent {
        char actor[32];
        int year;
        char title[32];
    };
    struct agent bond2;
    struct agent bond3;
    FILE *jbdb;

    /* open the file for appending */
    jbdb = fopen("bond.db","a");
    if(!jbdb)
    {
        puts("SPECTRE wins!");
        exit(1);
    }

    /* assign data */
    strcpy(bond2.actor,"Roger Moore");
    bond2.year = 1973;
    strcpy(bond2.title,"Live and Let Die");
    fwrite(&bond2,sizeof(struct agent),1,jbdb);

    strcpy(bond3.actor,"Pierce Brosnan");
    bond3.year = 1995;
    strcpy(bond3.title,"GoldenEye");
    fwrite(&bond3,sizeof(struct agent),1,jbdb);

    fclose(jbdb);
    puts("Records written");

    return(0);
}

Output

Records written

Notes

* The fopen() function at Line 17 uses the "a" mode to append data to the bond.db file.

* Because the data written isn't in an array, you need two fwrite() functions at Lines 28 and 33 to save the two structure variables to the file. If an array of structures were used instead, then you could write them both by using a single fwrite() function. Bonus For Dummies points are awarded if you coded this solution.

* Remember, your code need not look exactly like mine. Providing that the two structures were appended to the file, you're good. The real test is reading in the data.