61

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.

Palec
  • 12,743
  • 8
  • 69
  • 138
sparkFinder
  • 3,336
  • 10
  • 42
  • 57
  • @noɥʇʎPʎzɐɹC So the standard committee has established a standard required way to change the working directory, circa C++17, via `filesystem`. [pepper_chico's answer](http://stackoverflow.com/a/15215581/2642059) already denotes that. `filesystem` is currently available in g++5.3 and Visual Studio 2015 as an optional include. If that is the environment that you're working in I can write you an answer using `#ifdef` to make `filesystem`'s access cross platform? – Jonathan Mee Oct 25 '16 at 12:29
  • @JonathanMee if it is good enough, I may do a multiple bounty – noɥʇʎԀʎzɐɹƆ Oct 25 '16 at 22:11

9 Answers9

56

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
}
João Paulo
  • 6,300
  • 4
  • 51
  • 80
  • This changes only the current process's path. The operating shell's current path is not changed. – ecstrema Dec 07 '21 at 21:15
  • 6
    @MarcheRemi Yes, that's typically what's meant when you want to change the current working directory. Under most OSs, it's not possible to change any other process' working directory at all. – HiddenWindshield Feb 18 '22 at 15:41
53

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.

AndiDog
  • 68,631
  • 21
  • 159
  • 205
  • I'm asking since Visual Studio wants me to use direct.h, but when I try building the same code in Linux, it crashes on my head, saying that I need to use unistd.h – sparkFinder Aug 14 '10 at 21:50
  • 1
    @sparkFinder, you will usually need to include different headers on different platforms when dealing with nonstandard functions such as `chdir()`. IIRC, GCC will define `_WIN32` when targeting Windows, so you could use that with `#include` to choose a header. – RBerteig Aug 14 '10 at 22:16
  • 3
    @sparkFinder: You can check for Visual Studio with `#ifdef _MSC_VER` and then include the direct.h header. If it's not defined, use unistd.h. This should be enough as the other major programming environment on Windows, MinGW, has the unistd header. – AndiDog Aug 15 '10 at 14:24
  • You could just declare the prototype yourself. – R.. GitHub STOP HELPING ICE Aug 15 '10 at 18:14
  • 2
    `chdir` on windows is deprecated. – noɥʇʎԀʎzɐɹƆ Oct 20 '16 at 20:56
  • @noɥʇʎPʎzɐɹC Nothing about it being deprecated on [this page](https://msdn.microsoft.com/en-us/library/bf7fwze1.aspx). What's your source? – dbush Oct 24 '16 at 13:55
  • 1
    @dbush `_chdir != chdir` `_chdir` is not cross platform while `chdir` is deprecated. – Jonathan Mee Oct 24 '16 at 16:21
  • This answer is not correct as it promotes the use of a deprecated functionality as stated here https://msdn.microsoft.com/en-us/library/ms235420.aspx – siphr Oct 25 '16 at 22:15
21

For C++, boost::filesystem::current_path (setter and getter prototypes).

A file system library based on Boost.Filesystem will be added to the standard.

oblitum
  • 11,380
  • 6
  • 54
  • 120
20

This cross-platform sample code for changing the working directory using POSIX chdir and MS _chdir as recommend in this answer. Likewise for determining the current working directory, the analogous getcwd and _getcwd are used.

These platform differences are hidden behind the macros cd and cwd.

As per the documentation, chdir's signature is int chdir(const char *path) where path is absolute or relative. chdir will return 0 on success. getcwd is slightly more complicated because it needs (in one variant) a buffer to store the fetched path in as seen in char *getcwd(char *buf, size_t size). It returns NULL on failure and a pointer to the same passed buffer on success. The code sample makes use of this returned char pointer directly.

The sample is based on @MarcD's but corrects a memory leak. Additionally, I strove for concision, no dependencies, and only basic failure/error checking as well as ensuring it works on multiple (common) platforms.

I tested it on OSX 10.11.6, Centos7, and Win10. For OSX & Centos, I used g++ changedir.cpp -o changedir to build and ran as ./changedir <path>.

On Win10, I built with cl.exe changedir.cpp /EHsc /nologo.

MVP solution

$ cat changedir.cpp

#ifdef _WIN32
#include <direct.h>
// MSDN recommends against using getcwd & chdir names
#define cwd _getcwd
#define cd _chdir
#else
#include "unistd.h"
#define cwd getcwd
#define cd chdir
#endif

#include <iostream>

char buf[4096]; // never know how much is needed

int main(int argc , char** argv) {

  if (argc > 1) {
    std::cout  << "CWD: " << cwd(buf, sizeof buf) << std::endl;

    // Change working directory and test for success
    if (0 == cd(argv[1])) {
      std::cout << "CWD changed to: " << cwd(buf, sizeof buf) << std::endl;
    }
  } else {
    std::cout << "No directory provided" << std::endl;
  }

  return 0;
}

OSX Listing:

$ g++ changedir.c -o changedir
$ ./changedir testing
CWD: /Users/Phil
CWD changed to: /Users/Phil/testing

Centos Listing:

$ g++ changedir.c -o changedir
$ ./changedir
No directory provided
$ ./changedir does_not_exist
CWD: /home/phil
$ ./changedir Music
CWD: /home/phil
CWD changed to: /home/phil/Music
$ ./changedir /
CWD: /home/phil
CWD changed to: /

Win10 Listing

cl.exe changedir.cpp /EHsc /nologo
changedir.cpp

c:\Users\Phil> changedir.exe test
CWD: c:\Users\Phil
CWD changed to: c:\Users\Phil\test

Note: OSX uses clang and Centos gnu gcc behind g++.

Community
  • 1
  • 1
Phil
  • 1,226
  • 10
  • 20
9

Does chdir() do what you want? It works under both POSIX and Windows.

CharlesB
  • 86,532
  • 28
  • 194
  • 218
Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
5

You want chdir(2). If you are trying to have your program change the working directory of your shell - you can't. There are plenty of answers on SO already addressing that problem.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
5

Did you mean C or C++? They are completely different languages.

In C, the standard that defines the language doesn't cover directories. Many platforms that support directories have a chdir function that takes a char* or const char* argument, but even where it exists the header where it's declared is not standard. There may also be subtleties as to what the argument means (e.g. Windows has per-drive directories).

In C++, googling leads to chdir and _chdir, and suggests that Boost doesn't have an interface to chdir. But I won't comment any further since I don't know C++.

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
  • In boost::filesystem, there wasn't a "chdir" when I used it last time. – rubber boots Aug 14 '10 at 22:13
  • @rubber: indeed, looking at http://www.boost.org/doc/libs/1_34_1/boost/filesystem/operations.hpp suggests that there is a `getcwd` equivalent but no `chdir` equivalent. – Gilles 'SO- stop being evil' Aug 14 '10 at 22:22
  • I could see how one might think C and C++ were completely different languages if they were the only two languages you knew. or if C is the only language you knew – Michael Jan 15 '18 at 23:34
  • 1
    @Michael C and C++ have many characteristics in common: they're unsafe, imperative languages. They nonetheless are completely different languages, further apart than, say, C# and Java. It's true that C and C++ have a rather large common subset, but that common subset is almost never good C or good C++. If you think that C is a subset of C++, you're either a bad C programmer, or a bad C++ programmer, or both. – Gilles 'SO- stop being evil' Jan 15 '18 at 23:55
3

Nice cross-platform way to change current directory in C++ was suggested long time ago by @pepper_chico. This solution uses boost::filesystem::current_path().

To get the current working directory use:

namespace fs = boost::filesystem;
fs::path cur_working_dir(fs::current_path());

To set the current working directory use:

namespace fs = boost::filesystem;
fs::current_path(fs::system_complete( fs::path( "new_working_directory_path" ) ));    

Bellow is the self-contained helper functions:

#include "boost/filesystem/operations.hpp"
#include "boost/filesystem/path.hpp"
#include <string>

namespace fs = boost::filesystem;    

fs::path get_cwd_pth()
{
  return fs::current_path();
}   

std::string get_cwd()
{ 
  return get_cwd_pth().c_str();
} 

void set_cwd(const fs::path& new_wd)
{
  fs::current_path(fs::system_complete( new_wd));
}   

void set_cwd(const std::string& new_wd)
{
  set_cwd( fs::path( new_wd));
}

Here is my complete code-example on how to set/get current working directory:

#include "boost/filesystem/operations.hpp"
#include "boost/filesystem/path.hpp"
#include <iostream>

namespace fs = boost::filesystem;

int main( int argc, char* argv[] )
{
  fs::path full_path;
  if ( argc > 1 )
  {
    full_path = fs::system_complete( fs::path( argv[1] ) );
  }  
  else
  {
    std::cout << "Usage:   tcd [path]" << std::endl;
  }

  if ( !fs::exists( full_path ) )
  {
    std::cout << "Not found: " << full_path.c_str() << std::endl;
    return 1;
  }

  if ( !fs::is_directory( full_path ))
  {
    std::cout << "Provided path is not a directory: " << full_path.c_str() << std::endl;
    return 1;
  }

  std::cout << "Old current working directory: " << boost::filesystem::current_path().c_str() << std::endl;

  fs::current_path(full_path);

  std::cout << "New current working directory: " << boost::filesystem::current_path().c_str() << std::endl;
  return 0;
}

If boost installed on your system you can use the following command to compile this sample:

g++ -o tcd app.cpp -lboost_filesystem -lboost_system
Nikita
  • 6,270
  • 2
  • 24
  • 37
2

Can't believe no one has claimed the bounty on this one yet!!!

Here is a cross platform implementation that gets and changes the current working directory using C++. All it takes is a little macro magic, to read the value of argv[0], and to define a few small functions.

Here is the code to change directories to the location of the executable file that is running currently. It can easily be adapted to change the current working directory to any directory you want.

Code :

  #ifdef _WIN32
     #include "direct.h"
     #define PATH_SEP '\\'
     #define GETCWD _getcwd
     #define CHDIR _chdir
  #else
     #include "unistd.h"
     #define PATH_SEP '/'
     #define GETCWD getcwd
     #define CHDIR chdir
  #endif

  #include <cstring>
  #include <string>
  #include <iostream>
  using std::cout;
  using std::endl;
  using std::string;

  string GetExecutableDirectory(const char* argv0) {
     string path = argv0;
     int path_directory_index = path.find_last_of(PATH_SEP);
     return path.substr(0 , path_directory_index + 1);
  }

  bool ChangeDirectory(const char* dir) {return CHDIR(dir) == 0;}

  string GetCurrentWorkingDirectory() {
     const int BUFSIZE = 4096;
     char buf[BUFSIZE];
     memset(buf , 0 , BUFSIZE);
     GETCWD(buf , BUFSIZE - 1);
     return buf;
  }

  int main(int argc , char** argv) {

     cout << endl << "Current working directory was : " << GetCurrentWorkingDirectory() << endl;
     cout << "Changing directory..." << endl;

     string exedir = GetExecutableDirectory(argv[0]);
     ChangeDirectory(exedir.c_str());

     cout << "Current working directory is now : " << GetCurrentWorkingDirectory() << endl;

     return 0;
  }

Output :

c:\Windows>c:\ctwoplus\progcode\test\CWD\cwd.exe

Current working directory was : c:\Windows Changing directory... Current working directory is now : c:\ctwoplus\progcode\test\CWD

c:\Windows>

MarcD
  • 588
  • 3
  • 11