Is there a better way than simply trying to open the file?
int exists(const char *fname) { FILE *file; if ((file = fopen(fname, "r"))) { fclose(file); return 1; } return 0; }
access() Function to Check if a File Exists in C Another way to check if the file exists is to use the access() function. The unistd. h header file has a function access to check if the file exists or not. We can use R_OK for reading permission, W_OK for write permission and X_OK to execute permission.
To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .
The isDir() function is used to check a given file is a directory or not.
The file_exists() function checks whether a file or directory exists.
Look up the access()
function, found in unistd.h
. You can replace your function with
if( access( fname, F_OK ) == 0 ) { // file exists } else { // file doesn't exist }
You can also use R_OK
, W_OK
, and X_OK
in place of F_OK
to check for read permission, write permission, and execute permission (respectively) rather than existence, and you can OR any of them together (i.e. check for both read and write permission using R_OK|W_OK
)
Update: Note that on Windows, you can't use W_OK
to reliably test for write permission, since the access function does not take DACLs into account. access( fname, W_OK )
may return 0 (success) because the file does not have the read-only attribute set, but you still may not have permission to write to the file.
Use stat
like this:
#include <sys/stat.h> // stat #include <stdbool.h> // bool type bool file_exists (char *filename) { struct stat buffer; return (stat (filename, &buffer) == 0); }
and call it like this:
#include <stdio.h> // printf int main(int ac, char **av) { if (ac != 2) return 1; if (file_exists(av[1])) printf("%s exists\n", av[1]); else printf("%s does not exist\n", av[1]); return 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With