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.
To change the current working directory(CWD) os. chdir() method is used. This method changes the CWD to a specified path. It only takes a single argument as a new directory path.
The pwd command can be used to determine the present working directory. and the cd command can be used to change the current working directory.
Often, you may want to change the current working directory, so that you can access different subdirectories and files. To change directories, use the command cd followed by the name of the directory (e.g. cd downloads ). Then, you can print your current working directory again to check the new path.
The cd (“change directory”) command is used to change the current working directory in Linux and other Unix-like operating systems. It is one of the most basic and frequently used commands when working on the Linux terminal.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With