C faster way to check if a directory exists

后端 未结 5 1752
感动是毒
感动是毒 2020-12-09 16:23

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

相关标签:
5条回答
  • 2020-12-09 17:01

    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.

    0 讨论(0)
  • 2020-12-09 17:02

    I would use stat(), if available.

    0 讨论(0)
  • 2020-12-09 17:14

    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.

    0 讨论(0)
  • 2020-12-09 17:15

    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 */
        }
    }
    ...
    
    0 讨论(0)
  • 2020-12-09 17:18

    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.

    0 讨论(0)
提交回复
热议问题