0

I am writing a C++ program in which I change the working directory with std::filesystem::current_path(working_directory), where working_directory is a string. Is there a good way to, later in the program, reset the working directory to its original value? I understand that one solution would be to use a variable string initial_directory = std::filesystem::current_path() before I change the working directory and then later reset it with std::filesystem::current_path(initial_directory), but I feel like there should be a more elegant solution.

Thanks!

user4581301
  • 33,082
  • 7
  • 33
  • 54
  • 3
    Save it and set it back is the only way I know to do it. – Retired Ninja Jul 22 '21 at 20:35
  • 1
    I know of nothing in filesystem that does what you want and wouldn't expect it to exist. C++ has a policy of not making you pay for stuff you didn't ask for, and caching the original value of the working directory so that it can be restored later would be a cost that all users of filesystem would have to pay whether they needed it or not. There might be a target-specific API call that does this, but for portability's sake caching the original value and restoring it as needed seems the most-sane option. – user4581301 Jul 22 '21 at 20:37

1 Answers1

1

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';
}
Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27
  • There is zero reason to do it in `namespace std`, it just creates unnecessary confusion. – HolyBlackCat Jul 22 '21 at 21:10
  • @HolyBlackCat confusion aside, it indicates that you are pushing something related to the file system. – Vlad Feinstein Jul 22 '21 at 21:13
  • 1
    It also [causes undefined behavior](http://eel.is/c++draft/library#namespace.std-1) (which is mostly a formality here, but still). – HolyBlackCat Jul 22 '21 at 21:18
  • 1
    @HolyBlackCat - thinking about it, I found https://stackoverflow.com/questions/41062294/c-when-is-it-ok-to-extend-the-std-namespace; taking it back, will update the answer – Vlad Feinstein Jul 22 '21 at 21:19