代码之家  ›  专栏  ›  技术社区  ›  Debugger

如何在C/C++中获得ReDIR忽略目录?

  •  1
  • Debugger  · 技术社区  · 16 年前

    我正在阅读当前图书馆的内容 readdir ,但我只处理文件而不处理目录。我怎么知道我指向的是一个目录而不是一个文件?

    谢谢你

    2 回复  |  直到 9 年前
        1
  •  1
  •   Matthew Flaschen    16 年前

    你可以用 lstat S_ISDIR 宏。

    例如,不进行错误检查:

    struct stat buffer;
    int status;
    char path[PATH_MAX];
    DIR *dir = opendir(dir_name);
    ... 
    struct dirent *de = readdir(dir);
    sprintf(path, "%s/%s", dir_name, de->d_name);
    status = lstat(path, &buffer);
    if(S_ISDIR(buffer.st_mode))
    {
       ...
    }
    

    编辑:固定在lstat路径中包含目录(根据el.pescado)。正如R Samuel Klatchko所指出的,您可能希望采用白名单方法(s_isreg),而不是黑名单类型。

        2
  •  0
  •   user6762068    9 年前
    `void DirectryNFileCount(const char * FileDir)
     {
      DIR *dir;
      int filecount;
      int dircount;
      struct dirent *direntry;
      if ((dir = opendir (FileDir)) == NULL) 
      {
       /*Error code*/
       } 
     while((direntry = readdir (dir)) != NULL)
     {
     if(direntry->d_type==DT_DIR)
     dircount++;
    /*do something with directries      */
     }
     else 
     {
      filecount++;
      std::cout<<"Files Names"<<direntry->d_name<<std::endl; 
     }
     }
      std::cout<<"THIS Directory has "<<filecount<<" FILES and "<<dircount<< " DIRECTORIES";
    }
    
    推荐文章