Reputation: 1
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!
Upvotes: 0
Views: 840
Reputation: 11311
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';
}
Upvotes: 1