Another #define example
Comments and questions to John Rowe.
Our previous example of using
fopen() had an issue in that the file name
"highscore.txt" appeared twice. If we ever wanted to change it we
would have had to change it twice and the danger is that we would miss
one out.
Here is one solution using #define which demonstrates
that it can be used for text strings as well as mathematical constants.
The changes are shown highlighted.
#include <stdlib.h>
#include <stdio.h>
#define HSFILE "highscore.txt"
int readhighscore() {
int hs;
FILE *infile;
infile = fopen(HSFILE, "r");
if ( infile == NULL ) return 0;
fscanf(infile, "%d", &hs);
fclose(infile);
return hs;
}
void writehighscore(int hs) {
FILE *outfile;
if ( hs <= readhighscore())
return;
outfile = fopen(HSFILE, "w");
if ( outfile == NULL ) {
fprintf(stderr, "Cannot write high-score file\n");
exit(1);
}
fprintf(outfile, "%d", hs);
fclose(outfile);
}
int main() {
int highscore;
highscore = readhighscore();
printf("High score: %d\n", highscore);
writehighscore(12);
highscore = readhighscore();
printf("High score: %d\n", highscore);
writehighscore(2); return 0;
}
Step through this code
Log in