【问题标题】:How to reset filesystem::current_path() in C++17?如何在 C++17 中重置文件系统::current_path()?
【发布时间】:2021-09-30 02:36:30
【问题描述】:

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

谢谢!

【问题讨论】:

  • 保存并重新设置是我知道的唯一方法。
  • 我不知道文件系统中的任何内容都可以执行您想要的操作并且不希望它存在。 C++ 的政策是不让您为不需要的东西付费,并且缓存工作目录的原始值以便以后可以恢复,这将是所有文件系统用户都必须支付的费用,无论他们是否需要它与否。可能有一个特定于目标的 API 调用可以执行此操作,但为了可移植性,缓存原始值并根据需要恢复它似乎是最明智的选择。

标签: c++ directory std-filesystem


【解决方案1】:

自己动手做?

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

【讨论】:

  • namespace std 中这样做的理由为零,它只会造成不必要的混乱。
  • @HolyBlackCat 混淆,它表明你正在推送与文件系统相关的东西。
  • 它也是causes undefined behavior(这里主要是一种形式,但仍然如此)。
  • @HolyBlackCat - 想了想,我找到了stackoverflow.com/questions/41062294/…;收回它,将更新答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-13
  • 1970-01-01
相关资源
最近更新 更多