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 t
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.
I would use stat(), if available.
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.
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 */
}
}
...
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.