views:

142

answers:

3

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 is 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? 
+9  A: 

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.

catchmeifyoutry
Should have mentioned: trying to limit external dependencies, so no Boost please.
rubenvb
ah, ok. I will leave this comment then in case other people stumble upon this question ;)
catchmeifyoutry
+1  A: 

Calling getcwd with a NULL pointer is implementation defined. It often does the allocation for you with malloc (in which case your code does have a memory leak). However, it isn't guaranteed to work at all. So you should allocate your own buffer.

char *cwd_buffer = malloc(sizeof(char) * max_path_len);
char *cwd_result = getcwd(cwd_buffer, max_path_len);

The Open Group has an example showing how to get the max path length from _PC_PATH_MAX. You could consider using MAX_PATH on Windows. See this question for caveats to this number on both platforms.

Matthew Flaschen
Won't the std::string constructor free the malloc'ed memory?
rubenvb
@rubenvb, no, it just initializes the string to a copy. It has no way of knowing how the passed in `char *` was allocated.
Matthew Flaschen
Dang, OK, thanks
rubenvb
+2  A: 

You cannot call getcwd with a NULL buffer. As per the Opengroup:

If buf is a null pointer, the behavior of getcwd() is unspecified.

Also, getcwd can return NULL which can break a string constructor.

You'll need to change that to something like:

char buffer[SIZE];
char *answer = getcwd(buffer, sizeof(buffer));
string s_cwd;
if (answer)
{
    s_cwd = answer;
}
R Samuel Klatchko
If he's "only" interested in compatibility with Windows, Linux, and Max OS X, then `getcwd(NULL)` is well defined. They all extend the function the same way.
Rob Kennedy
I accepted this, but the above comment is imho correct. My code did have a memory leak though, so that needs solving
rubenvb
@RobKennedy - for Linux, it depends on the version being targeted. For example, on a RHEL5 box, the `getcwd(NULL)` is still documented as being undefined.
R Samuel Klatchko