Skip to content
Physics and Astronomy
Home Our Teaching Resources C programming #define example
Back to top

Another #define example

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"
//
// Read the high score from a file, returning zero
// if the file does not exist.
int readhighscore() {
  int hs;
  FILE *infile;

  infile = fopen(HSFILE, "r");
  if ( infile == NULL ) // First time game has been played
    return 0;

  fscanf(infile, "%d", &hs);

  fclose(infile);

  return hs;
}

//
// Write the high score file checking that this game's
// high score is greater than the saved one.
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); // Will do nothing
  return 0;
}
Step through this code


                                                                                                                                                                                                                                                                       

Validate   Link-check © Copyright & disclaimer Privacy & cookies Share
Back to top