如何在C++17中重置文件系统::current_path()



我正在编写一个C++程序,在该程序中,我用std::filesystem::current_path(working_directory)更改工作目录,其中working_directory是一个字符串。有没有一种好的方法可以在程序的后期将工作目录重置为其原始值?我知道一个解决方案是在更改工作目录之前使用变量string initial_directory = std::filesystem::current_path(),然后用std::filesystem::current_path(initial_directory)重置它,但我觉得应该有一个更优雅的解决方案。

谢谢!

DIY?

#include <iostream>
#include <filesystem>
#include <stack>
static std::stack<std::filesystem::path> s_path;
void pushd(std::filesystem::path path) {
s_path.push(std::filesystem::current_path());
std::filesystem::current_path(path);
}
void popd() {
if (!s_path.empty()) {
std::filesystem::current_path(s_path.top());
s_path.pop();
}
}
int main()
{
std::cout << "Current path is " << std::filesystem::current_path() << 'n';
pushd(std::filesystem::temp_directory_path());
std::cout << "Current path is " << std::filesystem::current_path() << 'n';
popd();
std::cout << "Current path is " << std::filesystem::current_path() << 'n';
popd();
std::cout << "Current path is " << std::filesystem::current_path() << 'n';
}

相关内容

最新更新