仅列出目录中的文件夹

m4t*_*4tx 20 c++ posix

我想列出C++目录中的文件夹,理想情况是在便携式(以主要操作系统工作)方式.我尝试使用POSIX,它工作正常,但我怎样才能确定找到的项目是否是文件夹?

dav*_*dag 26

您可以使用opendir()readdir()列出目录和子目录.以下示例打印当前路径中的所有子目录:

#include <dirent.h>
#include <stdio.h>

int main()
{
    const char* PATH = ".";

    DIR *dir = opendir(PATH);

    struct dirent *entry = readdir(dir);

    while (entry != NULL)
    {
        if (entry->d_type == DT_DIR)
            printf("%s\n", entry->d_name);

        entry = readdir(dir);
    }

    closedir(dir);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)


wal*_*lly 11

使用C++ 17 std::filesystem库:

std::vector<std::string> get_directories(const std::string& s)
{
    std::vector<std::string> r;
    for(auto& p : std::filesystem::recursive_directory_iterator(s))
        if (p.is_directory())
            r.push_back(p.path().string());
    return r;
}
Run Code Online (Sandbox Code Playgroud)

  • 我相信 `p.status().type() == std::filesystem::file_type::directory` 可以替换为 `p.is_directory()`,除非存在我不知道的细微差别。 (2认同)

Ben*_*oît 10

下面是来自boost文件系统文档的一个(略微修改过的)引用,向您展示如何完成它:

void iterate_over_directories( const path & dir_path )         // in this directory,
{
  if ( exists( dir_path ) ) 
  {
    directory_iterator end_itr; // default construction yields past-the-end
    for ( directory_iterator itr( dir_path );
          itr != end_itr;
          ++itr )
    {
      if ( is_directory(itr->status()) )
      {
        //... here you have a directory
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


Gra*_*row 5

查找stat功能.是一个描述.一些示例代码:

struct stat st;
const char *dirname = "dir_name";
if( stat( dirname, &st ) == 0 && S_ISDIR( st.st_mode ) ) {
    // "dir_name" is a subdirectory of the current directory
} else {
    // "dir_name" doesn't exist or isn't a directory
}
Run Code Online (Sandbox Code Playgroud)