C faster way to check if a directory exists

后端 未结 5 1829
感动是毒
感动是毒 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:15

    Consider using stat. S_ISDIR(s.st_mode) will tell you if it's a directory.

    Sample:

    #include 
    #include 
    #include 
    
    ...
    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 */
        }
    }
    ...
    

提交回复
热议问题