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 3:

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

Code:

    if (stat(file, &statbuf)) {
        printf("%s: No such file or directory\n", file);
        exit(1);
    }
    fp = fopen(file, "r");

Solution:

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

Comments:

Besides being shorter and clearer than the original, this solves some serious problems with the original:

First, you can't assume that the fopen() will succeed just because the stat succeeds. There are many possible reasons for fopen() to fail. The file might exist but not have read permission for the current user, for example. And even if you rule out all problems with the filesystem, there can be an i/o error, or you can run out of memory (fopen() does a malloc()).

Secondly, "no such file or directory" is not necessarily the correct error message. Use perror() to generate the correct error message based on what actually happened.

Which is another reason to error-check the fopen rather than the stat().

In general, don't test whether an operation will succeed before attempting the operation; just attempt the operation and diagnose errors correctly. It's simpler and it's more often correct.


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