Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C faster way to check if a directory exists

Tags:

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?

like image 451
Frederico Schardong Avatar asked Feb 16 '12 16:02

Frederico Schardong


2 Answers

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 */     } } ... 
like image 177
Johannes Weiss Avatar answered Oct 11 '22 19:10

Johannes Weiss


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.

like image 42
ckruse Avatar answered Oct 11 '22 17:10

ckruse