2011-02-18 97 views
19

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

回答

5

使用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.status().type() == std::filesystem::file_type::directory) 
      r.push_back(p.path().string()); 
    return r; 
} 
4

查找stat函数。 Here是一个描述。一些示例代码:

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 
} 
+0

OK,但它在Windows上工作? – m4tx 2011-02-18 16:17:02

+0

是:http://msdn.microsoft.com/en-us/library/14h5k7ff.aspx – 2011-02-18 16:31:27

2

我觉得不得不提到PhysFS。我只是将它集成到我自己的项目中。它提供真正的跨平台(Mac/Linux/PC)文件操作,甚至可以解压zip,7zip,pak等各种存档定义。它有几个功能(PHYSFS_isDirectoryPHYSFS_enumerateFiles),它可以确定你所要求的。

10

这里遵循了boost filesystem documentation(稍微修改)报价向您展示它是如何做:

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 
     } 
    } 
    } 
} 
+0

如何以字符串的形式获取目录名? – ar2015 2017-07-05 01:17:54

25

你可以使用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; 
} 
+0

您可以使用这些功能仅选择文件夹。我已经添加了一个例子来告诉你如何。 – 2011-02-18 16:12:18

1

在Windows下,你可以使用_findfirst()和_findnext()通过目录的内容进行迭代,然后用CreateFile()和GetFileInformationByHandle()以确定特定条目是否是目录或文件夹。 (是的,的CreateFile(),使用适当的参数,检查现有的文件。是不是生活盛大?)

仅供参考,一些类,我实现的代码,使用这些电话可以看出herehere

相关问题