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.

 

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.

 

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