Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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:

  • _getcwd at MSDN
  • getcwd at Kernel.org
  • getcwd at Apple.com

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?  
like image 240
rubenvb Avatar asked May 19 '10 19:05

rubenvb


People also ask

Which function is used to find current path of the directory?

The pwd command displays the full, absolute path of the current, or working, directory.

How do I get the directory that a program is running from?

For Windows system at console you can use system( dir ) command. And console gives you information about directory and etc. Read about the dir command at cmd .

Does path include current directory?

PATH The search path for commands. It is a colon-separated list of directories in which the shell looks for commands (see COMMAND EXECUTION below). A zero-length (null) directory name in the value of PATH indicates the current directory.

What is Getcwd in C?

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.


2 Answers

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(); 
like image 84
catchmeifyoutry Avatar answered Oct 28 '22 00:10

catchmeifyoutry


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; } 
like image 38
R Samuel Klatchko Avatar answered Oct 28 '22 00:10

R Samuel Klatchko