Solution for Exercise 22-8

ex2208

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

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

    handle = fopen("scores.dat","w");
    if(!handle)
    {
        puts("File error!");
        exit(1);
    }
    for(x=0;x<5;x++)
    {
        printf("High score #%d? ",x+1);
        scanf("%d",&highscore[x]);
    }
    fwrite(&highscore,sizeof(int),5,handle);
    fclose(handle);
    puts("Scores saved");
    return(0);
}

Notes

* The code prompts the user to input five high scores in the for loop at Line 16. Each value input is stored in the highscore array at Line 19. Because an individual array element is referenced, the & prefix is required.

* Line 21 writes all of the high score values to the file scores.dat in one blast.

* Another way to code this program would be to write each high score value as it's input. That can be done by adding a line in the for loop after the scanf() function:

That solution is also valid, although I wanted to show you how to write an array of int values to a file by using a single fwrite() function. Either solution is fine.