C check if file exists

It's impossible to check existence for certain in pure ISO standard C. There's no really good portable way to determine whether a named file exists; you'll probably have to resort to system-specific methods.


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

Tags:

C

C89