Checking a file exists in C
You could do something like this:
bool file_exists(const char * filename) {
if (FILE * file = fopen(filename, "r")) {
fclose(file);
return true;
}
return false;
}
Basically just open the file and check if it succeeded.
Existence: call stat()
, check the return code, which has no side effects. On UNIX, call access()
as well.
You would do this in the event you're simply doing what you asked, does FileA exist, not necessarily can I open it. Example: In UNIX a file with execute-only permissions would fail open, but still exist.
With stat
you can check st_mode for access. However since you intend to open the file anyway, fopen
or open
are probably what you want.
Try to open it:
FILE * file;
file = fopen("file_name", "r");
if (file){
//file exists and can be opened
//...
// close file when you're done
fclose(file);
}else{
//file doesn't exists or cannot be opened (es. you don't have access permission)
}