Solution for Exercise 22-9

ex2209

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

int main()
{
    FILE *handle;
    int highscore[5];
    int x;

    handle = fopen("scores.dat","r");
    if(!handle)
    {
        puts("File error!");
        exit(1);
    }
    fread(highscore,sizeof(int),5,handle);
    fclose(handle);
    for(x=0;x<5;x++)
        printf("High score #%d: %d\n",x+1,highscore[x]);
    return(0);
}

Output

High score #1: 500
High score #2: 480
High score #3: 420
High score #4: 390
High score #5: 125

Notes

* This code reads in the five int values regardless of whether they were written to the file individually or as a group.

* The & operator isn't required by the fread() function at Line 16 because highscore is an array. When single variables are used with fread() then you must supply the & operator to fetch that variable's address.

* The fread() function can also be used to read in one value at a time. If it were to do so in this code, say in a loop, the statement might look like this:

Because a single value highscore[x] is read, the & is required to reference the variable's address.