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);
}

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 is read, the & is required to reference the variable's address.

* Be aware that using fread() in binary mode on character data results in literal interpretation of the newline, which is different between Unix and Windows (MS-DOS) text files. In Unix, the 0x0a (\n) character is the newline; in Windows, 0x0d and 0x0a (\r\n) are used for the newline. You can override this interpretation by reading the file in non-binary mode (shown above). But reading in binary mode ("rb") directs fread() to fetch the literal values.