[ACCEPTED]-C faster way to check if a directory exists-opendir
Consider using stat
. S_ISDIR(s.st_mode)
will tell you if it's 1 a directory.
Sample:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
...
struct stat s;
int err = stat("/path/to/possible_dir", &s);
if(-1 == err) {
if(ENOENT == errno) {
/* does not exist */
} else {
perror("stat");
exit(1);
}
} else {
if(S_ISDIR(s.st_mode)) {
/* it's a dir */
} else {
/* exists but is no dir */
}
}
...
You could call mkdir()
. If the directory does not 3 exist then it will be created and 0
will 2 be returned. If the directory exists then 1 -1
will be returned and errno
will be set to EEXIST
.
I prefer using access()
if (0 != access("/path/to/possible_dir/", F_OK)) {
if (ENOENT == errno) {
// does not exist
}
if (ENOTDIR == errno) {
// not a directory
}
}
If you ensure a trailing 1 /
in the directory name, this works perfectly.
I would use stat()
, if available.
0
It sounds like you have a memory leak. Calling 5 opendir should not inflate the RAM of your 4 app as long as you remember to always call 3 closedir after successfully opening a directory. Also, make 2 sure you are freeing any buffers you allocated 1 to compute the directory name.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.