如何解决如何将STD :: filesystem :: recursive_directory_iterator与相对路径一起使用?
我正在尝试在文件系统中使用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;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。