首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从C:/递归获取所有文件

从C:/递归获取所有文件
EN

Stack Overflow用户
提问于 2021-07-20 18:59:47
回答 1查看 237关注 0票数 0

我试图使用Boost库从C:/目录检索所有文件。

当输入是带有目录的文件路径(例如: C:\Windows)时,我可以检索所有文件,但是当指定的路径仅为C:**时,我会得到一个错误。我也尝试过使用C:**,但是从我的项目目录而不是从根目录提升搜索文件。

我还为C:\Windows添加了一个排除项,这个部分工作得很好。

那么如何从**C:**启动recursive_directory_iterator呢?

这是我的代码:

代码语言:javascript
复制
//string rootPath = boost::filesystem::current_path().root_directory().string();
string rootPath = "C:";
string exclusionPath = rootPath+"\\"+"Windows";

void myClass::getFile()
{ 

   for (boost::filesystem::recursive_directory_iterator end, dir(rootPath); dir != end; ++dir)
   {   

    string filePath = dir->path().string();
    
    if (boost::filesystem::is_regular_file(*dir) && filePath.find(exclusionPath) == string::npos)
    {
        cout << filePath << endl;
    }
  }
}
EN

回答 1

Stack Overflow用户

发布于 2021-07-20 19:47:06

如果使用的是c++17标准库,则可以利用标准文件系统库。它的工作方式类似于boost文件系统,这两个库的API非常相似。您必须将文件系统头包含在

代码语言:javascript
复制
#include <filesystem>

通过调用以下命令,可以递归地遍历目录中的每个文件:

代码语言:javascript
复制
for (std::filesystem::directory_entry entry : std::filesystem::recursive_directory_iterator(rootPath))

这将给您一个目录条目,它就像boost目录条目一样,包含一个路径。我能够用标准库复制您的示例代码,并得到了如下所示的工作示例:

代码语言:javascript
复制
#include <filesystem>
#include <string>
#include <iostream>

std::filesystem::path rootPath = "C:";
std::filesystem::path exclusionPath = rootPath / "Windows";

int main()
{
    for (std::filesystem::directory_entry entry : std::filesystem::recursive_directory_iterator(rootPath))
    {
        std::string filePath = entry.path().string();

        if (std::filesystem::is_regular_file(entry.path()) && filePath.find(exclusionPath.string()) == std::string::npos)
        {
            std::cout << filePath << std::endl;
        }
    }
}

如您所见,我将用于以上路径的字符串转换为路径。这不是必要的,但最好是预先构造一个路径,因为否则您调用的每个函数都会用您放入的字符串构造一个新路径。路径奇怪地使用/运算符将两条路径附加在一起,例如在Windows上

代码语言:javascript
复制
std::filesystem::path exclusionPath = rootPath / "Windows";

会给你C:\Windows

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68460077

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档