Reputation: 7600
I have a C string that I want to use to open that file. How do I determine if the file exists?
Upvotes: 1
Views: 297
Reputation: 612
Everyone's answers are valid (with minor tweeks) here but make some assumptions. First, if it actually a file your checking or is it possibly a file/directory/symlink/fifo/socket/etc. If it's just a file, the fopen(), stat() and access() solutions won't work.
fopen() will succeed on nearly all object types in many operating systems (including a valid directory), while stat() and access() will most certainly success regardless of filesystem object type in all operating systems (they will always succeed is a filesystem object exists and is accessable in the current security context [logged in user]). Even worse, windows compilers will treat stat differently (because they either link to msvc's lib or they inline their own implemenation).
Sadly, your best approach (if determining if a file exists and you want to be portable) is something like...
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/stat.h>
#include <unistd.h>
#endif
int file_exists(const char* filename) {
#ifdef _WIN32
HANDLE h = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
if (h == INVALID_HANDLE_VALUE)
return 0;
int res = 0;
if (GetFileType(h) == FILE_TYPE_DISK)
res = 1;
CloseHandle(h);
return res;
#else
struct stat st;
if (stat(filename, &st) == -1)
return 0;
return S_ISREG(st.st_mode);
#endif
return 0;
}
Upvotes: 1
Reputation: 19353
You could also use stat
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
struct stat s;
if (stat("/path/to/file", &s) == -1) {
printf("Invalid path\n");
} else {
printf("Valid path\n");
}
return 0;
}
This does not tell you whether your program has permissions to read or write the file (fopen()
is good for that) but this will tell you whether or not the path exists.
Upvotes: 0
Reputation: 23858
Use the function called access()
if(access(file_path, F_OK)==0)
//file exists
else
// file does not exists
Upvotes: 5
Reputation: 3766
In most cases it is easiest to just open the file for writing. If there is a problem you will get a NULL file handle back.
#include <stdio.h>
int fileExists(const char* path) {
FILE* f = fopen(path, "rb");
if (!f) {
return 0;
}
fclose(path);
return 1;
}
Of course, if you are going to want to read from the file, you shouldn't fclose() the handle immediately.
Upvotes: 0