问题描述
我正在尝试在文件系统中使用recursive_directory_iterator,但收到一条错误消息。我的main.cpp文件位于“ A / main.cpp”文件中,但我想访问“ B /”中的一堆.txt文件。 A和B文件夹都位于同一级别的目录中。因此,我假设从A到B的相对路径是:“ ./ B /”或“ ../ B /”
这是我的代码:
#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
解决方法
先设置当前路径。当 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;
}
}