Existence of a file given its path
Given the path, is ther开发者_C百科e a way to find out whether the file exists without opening the file?
Thanks
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.
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");
}
}
#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().
Try to remove it (unlink()). If successful, it doesn't exist anymore. If unsuccessful, interpret errno to see if it exists :)
精彩评论