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; }
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Look up the
access()function, found inunistd.h. You can replace your function withUnder Windows (VC)
unistd.hdoes not exist. To make it work it is necessary to define:You can also use
R_OK,W_OK, andX_OKin place ofF_OKto 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 usingR_OK|W_OK)Update: Note that on Windows, you can’t use
W_OKto 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.