我想在C++中列出目录中的文件夹,最好是以可移植(在主要操作系统上工作)的方式。我尝试使用POSIX,它工作正常,但是我如何识别找到的项目是否是文件夹?
发布于 2017-10-05 23:44:57
使用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;
}
发布于 2011-02-19 00:01:15
您可以使用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;
}
发布于 2011-02-18 23:56:57
下面是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
}
}
}
}
https://stackoverflow.com/questions/5043403
复制相似问题