Reputation: 3904
Given the path, is there a way to find out whether the file exists without opening the file?
Thanks
Upvotes: 3
Views: 405
Reputation: 44250
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
int rc;
struct stat mystat;
rc = stat(path, &mystat);
Now check rc and (maybe) errno.
EDIT 2011-09-18 addendum:
Both access() and stat() return 0 if the path points to a non-file (directory, fifo,symlink, whatever)
In the stat() case, this can be tested with "((st_mode & S_IFREG) == S_IFREG)". Best way still is to just try to open the file with open() or fopen().
Upvotes: 1
Reputation: 215627
The most efficient way is access
with the F_OK
flag.
stat
also works but it's much heavier weight since it has to read the inode contents, not just the directory.
Upvotes: 7
Reputation: 206646
You can use the stat system call. Make sure though that you check errno
for the correct error because stat
may return -1
for a number of other reasons/Failures.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
main()
{
struct stat BUF;
if(stat("/Filepath/FileName",&BUF)==0)
{
printf("File exists\n");
}
}
Another way is by using the access function.
#include <unistd.h>
main()
{
if(access("/Filepath/FileName", F_OK) != -1 )
{
printf("File exists\n");
}
else
{
printf("File does not exist\n");
}
}
Upvotes: 3
Reputation: 121
Try to remove it (unlink()). If successful, it doesn't exist anymore. If unsuccessful, interpret errno to see if it exists :)
Upvotes: -1