C check if file exists

c c89
The GiG picture The GiG · Apr 21, 2011 · Viewed 18.4k times · Source

In a project I have to do in C89 standard I have to check if a file exists. How do I do this?

I thought of using

FILE *file;
if ((file = fopen(fname, "r")) == NULL)
{
  printf("file doesn't exists");
}
return 0;

but I think there can be more cases then file doesn't exists that will do fopen == NULL.

How do I do this? I prefer not using includes rather then .

Answer

onitake picture onitake · Apr 21, 2011

If you can't use stat() in your environment (which is definitely the better approach), just evaluate errno. Don't forget to include errno.h.

FILE *file;
if ((file = fopen(fname, "r")) == NULL) {
  if (errno == ENOENT) {
    printf("File doesn't exist");
  } else {
    // Check for other errors too, like EACCES and EISDIR
    printf("Some other error occured");
  }
} else {
  fclose(file);
}
return 0;

Edit: forgot to wrap fclose into a else