Total Pageviews

Monday, May 10, 2010

Lesson 3 - C/C++: How to obtain the full path of current directory?

#include // for getcwd
#include // for MAX_PATH
#include // for cout and cin

using namespace std;

// function to return the current working directory
// this is generally the application path
void GetCurrentPath(char* buffer)
{
getcwd(buffer, _MAX_PATH);
}

int main()
{

// _MAX_PATH is the maximum length allowed for a path
char CurrentPath[_MAX_PATH];
// use the function to get the path
GetCurrentPath(CurrentPath);

// display the path for demo purposes only
char temp[_MAX_PATH];
cout << CurrentPath << endl; cout << "Press Enter to continue"; cin.getline(temp,_MAX_PATH); return 0; } 



 #include /* defines FILENAME_MAX */
#ifdef WINDOWS
#include
#define GetCurrentDir _getcwd
#else
#include
#define GetCurrentDir getcwd
#endif

char cCurrentPath[FILENAME_MAX];

if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
{
return errno;
}

cCurrentPath[sizeof(cCurrentPath) - 1] = '/0'; /* not really required */

printf ("The current working directory is %s", cCurrentPath);

Here's code to get the full path to the executing app:

Windows:

int bytes = GetModuleFileName(NULL, pBuf, len);
if(bytes == 0)
return -1;
else
return bytes;
Linux:

char szTmp[32];
sprintf(szTmp, "/proc/%d/exe", getpid());
int bytes = MIN(readlink(szTmp, pBuf, len), len - 1);
if(bytes >= 0)
pBuf[bytes] = '\0';
return bytes;

Maybe concatenate the current working directory with argv[0]? I'm not sure if that would work in Windows but it works in linux.

For example:

#include
#include
#include

int main(int argc, char **argv) {
char the_path[256];

getcwd(the_path, 255);
strcat(the_path, "/");
strcat(the_path, argv[0]);

printf("%s\n", the_path);

return 0;
}

No comments:

Post a Comment