If fopen
returns NULL, then the file isn't open; you're passing NULL
in to ferror
, which is invalid. You don't have an open file to pass in; that's what NULL
means, that it couldn't give you a file pointer. ferror
is for getting errors related to reading and writing the file, once it has actually been opened and you have the file to work with.
If fopen
fails, and you want to get more information about why, you need to check the errno
global variable, defined in errno.h
.
#include <errno.h>
// ...snip...
if (file == NULL)
printf("Error READING FILE: %s\n", strerror(errno));
This example shows how to fetch a string describing the error; you could also compare the value in errno
against one of the possible values it could have, and do something different depending on what the error is. See the fopen
man page, or the POSIX spec, for a list of possible errors to compare against. Here's how you could check against various possible errors:
if (file == NULL) {
int error = errno; // copy it so other calls like printf don't modify it
printf("Error READING FILE: %s\n", strerror(error));
switch (error) {
case EACCESS:
// access was denied
break;
case ENOENT:
// the file or one of its ancestors doesn't exist
break;
// etc...
}
}
(this is an expansion of something I originally wrote in a comment on another answer)