Change the current working directory in C++
How can I change my current working directory in C++ in a platform-agnostic way?
I found the direct.h
header file, which is Windows compatible, and the unistd.h
, which is UNIX/POSIX compatible.
The chdir
function works on both POSIX (manpage) and Windows (called _chdir
there but an alias chdir
exists).
Both implementations return zero on success and -1 on error. As you can see in the manpage, more distinguished errno values are possible in the POSIX variant, but that shouldn't really make a difference for most use cases.
Now, with C++17 is possible to use std::filesystem::current_path
:
#include <filesystem>
int main() {
auto path = std::filesystem::current_path(); //getting path
std::filesystem::current_path(path); //setting path
}