问题
I'm using opendir function to check if a directory exists. The problem is that I'm using it on a massive loop and it's inflating the ram used by my app.
What is the best (fastest) way to check if a directory exists in C? What is the best (fastest) way to create it if doesn't exists?
回答1:
You could call mkdir()
. If the directory does not exist then it will be created and 0
will be returned. If the directory exists then -1
will be returned and errno
will be set to EEXIST
.
回答2:
Consider using stat. S_ISDIR(s.st_mode)
will tell you if it's 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 */
}
}
...
回答3:
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 /
in the directory name, this works perfectly.
回答4:
I would use stat()
, if available.
回答5:
It sounds like you have a memory leak. Calling opendir should not inflate the RAM of your app as long as you remember to always call closedir after successfully opening a directory. Also, make sure you are freeing any buffers you allocated to compute the directory name.
来源:https://stackoverflow.com/questions/9314586/c-faster-way-to-check-if-a-directory-exists