fopen actually trying to open a file that you cannot make if you do not have read access. To check if a file exists without opening it, use stat ; stat gives you metadata about the file and requires only read access to the directory containing the file, not the file itself.
int doesFileExist(const char *filename) { struct stat st; int result = stat(filename, &st); return result == 0; }
You can fall in love by checking errno if result not 0; if errno is ENOENT , then the file does not exist, if it is ENOTDIR , then part of the path you provided is not a directory, if it is EACCESS , then you did not have permission to read on one of the directories in the path, and therefore stat cannot give you an answer etc.
Also, keep in mind that if you are on a platform with symbolic links (any Unix-like or Windows Vista or later), you should know if you are requesting a link to a symbolic link or the file to which it points. If you call stat , then you ask about the file that it points to; if you have a dir/link symbolic link that points to other/file , then stat will return the results about other/file (usually this is what you want, since this is what you would get if you opened the file). However, if you are interested in learning about the link itself (if you want to know if dir/link exists, even if there is no other/file ? "), Then you should use lstat() .
stat() works on Windows as a compatibility shell (they prefer to use _stat() and will warn you if you donโt), but itโs usually better to use platform-based APIs. On Windows, you should probably use GetFileAttributes() :
int doesFileExist(const char *filename) { return GetFileAttributes(filename) != INVALID_FILE_ATTRIBUTES; }
Brian campbell
source share