Skip to content
Physics and Astronomy
Home Our Teaching Resources C programming fopen() example
Back to top
On this page
Contents

Input and Output example

Although we shall often show code that calls exit() when unable to open a file it's important to notice there are situations where this is perfectly OK.

For example, a game may have a file to contain the high-score but the first time the game is played this file may not exist. It's important that the program does something sensible in this situation rather than just quit.

The following function tries to read the high score from a file and assumes a default high-score of zero if the high-score file does not exist.

#include <stdio.h>
//
// Read the high score from a file, returning zero
// if the file does not exist.
int readhighscore() {
  int hs;
  FILE *infile;

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

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

  fclose(infile);

  return hs;
}

Showing both behaviours

Finally, this longer example shows the writehighscore() function (notice that it is an error not to be able to write to the file) and stepping through the code demonstrates the behaviour when the file is and isn't present.

#include <stdlib.h>
#include <stdio.h>
//
// Read the high score from a file, returning zero
// if the file does not exist.
int readhighscore() {
  int hs;
  FILE *infile;

  infile = fopen("highscore.txt", "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("highscore.txt", "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


Note

This code has an issue in that the file name "highscore.txt" appears twice. If we ever want to change it we will have to change it twice and the danger is that we will miss one out. This is a common problem when programming and we shall see one solution to it next week.

Log in
                                                                                                                                                                                                                                                                       

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