1

我正在尝试在文件系统中使用 recursive_directory_iterator,但我收到一条错误消息。我的 main.cpp 文件在“A/main.cpp”文件中,但我想访问“B/”中的一堆 .txt 文件。A & B 文件夹都位于同一级目录中。所以,我假设从 A 到 B 的相对路径是:“./B/”或“../B/”</p>

这是我的代码:

#include <iostream>
#include <experimental/filesystem>

using namespace std;

int main()
{
 //Absolute path works

    for (auto& file : std::filesystem::recursive_directory_iterator("/Users/Tonny/Desktop/Project/B/"))
    {
        cout<< “Through absolute path: “ << file.path() << endl;
    }
//Relative path doesn’t work
    for (auto& file : std::filesystem::recursive_directory_iterator("../B/"))
    {
        cout << “Through relative path: “ << file.path() << endl;
    }
}

但是,在尝试两者时出现以下错误:

libc++abi.dylib:以 std::__1::__fs::filesystem::filesystem_error 类型的未捕获异常终止:文件系统错误:在 recursive_directory_iterator 中:没有这样的文件或目录 [../B]

这是我的编译器版本:

gcc --version

Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 11.0.3 (clang-1103.0.32.62)
Target: x86_64-apple-darwin19.6.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
4

1 回答 1

1

首先设置当前路径。recursive_directory_iterator(...)当参数为空或相对路径时,系统假定当前设置的路径。

std::filesystem::current_path("/Users/Tonny/Desktop/Project/B/");  //set cur path first

for (auto& file : std::filesystem::recursive_directory_iterator("../B/"))
{
    cout << “Through relative path: “ << file.path() << endl;
}

选择:

如果您不想弄乱current_path(),至少跟踪您的目标路径,然后将相对路径连接到该路径字符串。

#include <iostream>
#include <experimental/filesystem>

using namespace std;
namespace fs = std::experimental::filesystem;

int main()
{
    
    std::string targetPath = "/Users/Tonny/Desktop/Project/B/";

    
     //Absolute path
    for (auto& file : fs:recursive_directory_iterator(targetPath))
    {
        cout<< “Through absolute path: “ << file.path() << endl;
    }
    
    //Relative path
    for (auto& file : fs::recursive_directory_iterator(targetPath + "../B/"))
    {
        cout << “Through relative path: “ << file.path() << endl;
    }
}
于 2021-05-12T05:36:50.017 回答