Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 555
sparkFinder Avatar asked Aug 14 '10 21:08

sparkFinder


People also ask

How do I change my current working directory?

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.

Which command is used to change the current directory?

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.

How do I change the working directory in a script?

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.

Which Linux command is used to change the current working directory?

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.


2 Answers

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.

like image 99
AndiDog Avatar answered Oct 01 '22 03:10

AndiDog


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 } 
like image 22
João Paulo Avatar answered Oct 01 '22 01:10

João Paulo