Lab overview
Lab 01
Lab 02
Lab 03
Lab 04
Lab 05
Lab 06
Lab 07
Lab 08
Lab 09
Lab 10
Lab 11
Lab 12
Lab 13
Review

[Course home page]

CSC 209 lab 10 solutions, week of 19 July 2022

Question 4:

Problem:
Open a file and terminate with an error if it doesn't exist (same problem):

Code:

    if ((fp = fopen(file, "r")) == NULL) {
        perror("opening the file");
        exit(1);
    }

Solution:

Of course the solution here is the same as in the previous problem, namely:

    if ((fp = fopen(file, "r")) == NULL) {
	perror(file);
	exit(1);
    }

The only defect in the original code this time is the way in which perror() is used. The argument to perror() should be a file name if one is available. The original code will generate a message like this (assuming the "file" variable contains the value "hello.c"):

	opening the file: Permission denied
whereas the revised version will look like:
	hello.c: Permission denied
The latter is a standard error message, and is more informative.

Don't underestimate the value of standardization. If every unix utility output error messages in a different format, unix would be a lot harder to become expert in.

And don't attempt creativity in this realm. There are many ways to be creative in computer programming which are more exciting than producing substandard error messages.


[press 'back' in your web browser to return to the problems]