Solution for Exercise 22-7

ex2207

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

int main()
{
    FILE *handle;
    int highscore;

    handle = fopen("scores.dat","w");
    if(!handle)
    {
        puts("File error!");
        exit(1);
    }
    printf("What is your high score? ");
    scanf("%d",&highscore);
    fwrite(&highscore,sizeof(int),1,handle);
    fclose(handle);
    puts("Score saved");
    return(0);
}

Notes

* The fwrite() function saves the int value in variable highscore to a file. The value is saved as an int — a four byte binary value. (Well, four bytes on my computer.)

* If the code cannot find scores.dat, place a copy of that file into the executable folder in Code::Blocks for this exercise. The pathname is something like ../BegC4D/ex2207/bin/Release/

* Also see the Solution for Exercise 22-6 if you're concerned that the mode string should be "wb" instead of "w".