Skip to content

Instantly share code, notes, and snippets.

@sailfish009
Created January 20, 2019 01:35
Show Gist options
  • Select an option

  • Save sailfish009/96914ea0dba359f5a66f7d6671af89e2 to your computer and use it in GitHub Desktop.

Select an option

Save sailfish009/96914ea0dba359f5a66f7d6671af89e2 to your computer and use it in GitHub Desktop.
https://stackoverflow.com/questions/2203159/is-there-a-c-equivalent-to-getcwd
std::string's constructor can safely take a char* as a parameter. Surprisingly there's a windows version too.
Edit: actually it's a little more complicated:
std::string get_working_path()
{
char temp[MAXPATHLEN];
return ( getcwd(temp, sizeof(temp)) ? std::string( temp ) : std::string("") );
}
Memory is no problem -- temp is a stack based buffer, and the
std::string constructor does a copy. Probably you could do it in one go,
but I don't think the standard would guarantee that.
About memory allocation, via POSIX:
The getcwd() function shall place an absolute pathname of the
current working directory in the array pointed to by buf, and return
buf. The pathname copied to the array shall contain no
components that are symbolic links. The size argument is the size in
bytes of the character array pointed to by the buf argument. If buf is a
null pointer, the behavior of getcwd() is unspecified.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment