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.