Change the current working directory in C++

C++HeaderPortabilityWorking Directory

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

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
}

Solution 3 - C++

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

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

Solution 4 - C++

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++.

Solution 5 - C++

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

Solution 6 - C++

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.

Solution 7 - C++

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++.

Solution 8 - C++

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

Solution 9 - C++

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsparkFinderView Question on Stackoverflow
Solution 1 - C++AndiDogView Answer on Stackoverflow
Solution 2 - C++João PauloView Answer on Stackoverflow
Solution 3 - C++pepper_chicoView Answer on Stackoverflow
Solution 4 - C++PhilView Answer on Stackoverflow
Solution 5 - C++Jeremy FriesnerView Answer on Stackoverflow
Solution 6 - C++Carl NorumView Answer on Stackoverflow
Solution 7 - C++Gilles 'SO- stop being evil'View Answer on Stackoverflow
Solution 8 - C++NikitaView Answer on Stackoverflow
Solution 9 - C++MarcDView Answer on Stackoverflow