如何在 C++17 中重置 filesystem::current_path()?

问题描述

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

谢谢!

解决方法

自己动手做?

#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';
}