Using PellesC on Windows 8.1.
I know this topic has been addressed many times with many solutions. I have read solutions stating the usage of CreateFile
, PathFileExists
, GetFileAttributes
, _access
which I somewhat understand.
I have also read an important point about race conditions in the answer to the questions Quickest way to check whether or not file exists and What's the best way to check if a file exists in C? (cross platform).
So if I open a file using fopen()
in C and when it fails (for any reason) and passes NULL
back; then can I further check for errno == ENOENT
and be content with it and report correctly that the file does not exists.
#include <stdio.h>
#include <string.h>
#include <errno.h>
int file_exists(char filename[]) {
int err = 0; //copy of errno at specific instance
int r = 0; //1 for exists and 0 for not exists
FILE *f = NULL;
//validate
if (filename == NULL) {
puts("Error: bad filename.");
return 0;
}
printf("Checking if file %s exists...\n", filename);
//check
errno = 0;
f = fopen(filename, "r");
err = errno;
if (f == NULL) {
switch (errno) {
case ENOENT:
r = 0;
break;
default:
r = 1;
}
printf("errno = %d\n%s\n", err, strerror(err));
} else {
fclose(f);
r = 1;
}
if (r == 0) {
puts("It does not.");
} else {
puts("It does.");
}
return r;
}