How to check if a dir exists?
How would I go about checking if a FILE is a directory? I have
if (file == NULL) {
fprintf(stderr, "%s: No such file\n", argv[1]);
return 1;
}
and that checks if the node exists at all, but I want to know i开发者_如何学JAVAf it's a dir or a file.
Filenames themselves don't carry any information about whether they exist or not or whether they are a directory with them - someone could change it out from under you. What you want to do is run a library call, namely stat(2), which reports back if the file exists or not and what it is. From the man page,
[ENOENT] The named file does not exist.
So there's an error code which reports (in errno) that the file does not exist. If it does exist, you may wish to check that it is actually a directory and not a regular file. You do this by checking st_mode in the struct returned:
The status information word st_mode has the following bits:
...
#define S_IFDIR 0040000 /* directory */
Check the manpage for further information.
struct stat st;
if(stat("/directory",&st) == 0)
printf(" /directory is present\n");
use opendir to try and open it as a directory. If that returns a null pointer it's clearly not a directory :)
Here's a snippet for your question:
#include <stdio.h>
#include <dirent.h>
...
DIR *dip;
if ((dip = opendir(argv[1])) == NULL)
{
printf("not a directory");
}
else closedir(dip);
If you're using *nix, stat().
精彩评论