如何使用 in C++ 访问相对父目录<filesystem>

How to access the relative parent directory using <filesystem> in C++

本文关键字:gt lt filesystem in 何使用 C++ 访问 相对      更新时间:2023-10-16

我想知道如何使用<filesystem>标头访问当前工作目录的父目录C++ 17.然后我想从父目录重定向到另一个文件夹以搜索文件。

下面是一个概念示例:

#include <iostream>
#include <filesystem>
using namespace std;
int main()
{
namespace fs = std::filesystem;
fs::path working_dir(fs::current_path());
fs::path parent_path(
// ... Get path to parent dir of current working dir ... //
);
fs::current_path(parent_path);
fs::current_path(
// ... Redirect to subfolder called "sub_fold" ... //
);
// ... Search for specified file called "sub_file" to see if it exists ... //
if (sub_file.exists())  // Psudo-code for returning if "sub_file" exists
{
// ... Do stuff with "sub_file" ... //
}
else cout << "File does not exist in " << fs::current_path << endl;
fs::current_path(working_dir);
// ... Continue program ... //
return 0;
}

>working_dir.parent_path()会带你进入父目录 - 但一定要先检查它是否存在。

working_dir / "sub_fold"应该会让你进入子目录。

此信息由 cppreference.com 提供