微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 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';
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。