【问题标题】:Get all file recursively from C:/从 C:/ 递归获取所有文件
【发布时间】:2021-07-20 18:59:47
【问题描述】:

我正在尝试使用 Boost 库从 C:/ 目录中检索所有文件。

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

我还向 C:\Windows 添加了一个排除项,这部分效果很好。

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

这是我的代码:

//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;
    }
  }
}

【问题讨论】:

  • 不要为此使用 boost,你现在有一个 standard C++ way。所以问题here
  • 您声明"...but I get an error when the specified path is only C:\":请将错误逐字显示为文本。
  • @G.M.这是我得到的错误:program.exe 中 0x00007FFA48BA4ED9 处的未处理异常:Microsoft C++ 异常:内存位置 0x000000B9796FF020 处的 boost::filesystem::filesystem_error。
  • @MichaelChourdakis,好的,我将测试标准库,但我发现 boost 更快,我不知道
  • @Sad1que filesystem_error 有几个非静态成员来描述底层操作系统错误(native_error()error()who()what()path1())。他们实际上在说什么?您指定的路径一开始就错误,或者您可能没有访问它的安全权限。

标签: c++ boost-filesystem


【解决方案1】:

如果您使用的是 c++17 标准库,则可以利用标准文件系统库。它就像 boost 文件系统一样工作,并且两个库具有非常相似的 API。 您必须通过

包含文件系统标头
#include <filesystem>

您可以通过调用递归遍历目录中的每个文件:

for (std::filesystem::directory_entry entry : std::filesystem::recursive_directory_iterator(rootPath))

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

#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 上

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

会给你C:\Windows

【讨论】:

    猜你喜欢
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 2017-05-18
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多