c++cross-platformgetcwd

What is a cross-platform way to get the current directory?


I need a cross-platform way to get the current working directory (yes, getcwd does what I want). I thought this might do the trick:

#ifdef _WIN32
    #include <direct.h>
    #define getcwd _getcwd // stupid MSFT "deprecation" warning
#elif
    #include <unistd.h>
#endif
#include <string>
#include <iostream>
using namespace std;

int main()
{
    string s_cwd(getcwd(NULL,0));
    cout << "CWD is: " << s_cwd << endl;
}

I got this reading:

There should be no memory leaks, and it should work on a Mac as well, correct?

UPDATE: I fear something is still wrong here (I'm trying to avoid creating a char array with a determined length, as there's no proper way to get a decent length for getcwd):

char* a_cwd = getcwd(NULL,0);
string s_cwd(a_cwd);
free(a_cwd); // or delete a_cwd? 

Solution

  • If it is no problem for you to include, use boost filesystem for convenient cross-platform filesystem operations.

    boost::filesystem::path full_path( boost::filesystem::current_path() );
    

    Here is an example.

    EDIT: as pointed out by Roi Danton in the comments, filesystem became part of the ISO C++ in C++17, so boost is not needed anymore:

    std::filesystem::current_path();