1

Possible Duplicate:
Get path of executable

I have an application on C++, how can I get my full directory (where .exe file of this application exists)?

Edit: OS - Windows

Community
  • 1
  • 1
Roman
  • 1,377
  • 2
  • 11
  • 12

2 Answers2

1

Windows:

WCHAR path[MAX_PATH];
GetModuleFileName(NULL, path, ARRAYSIZE(path));

Linux:

char buffer[MAX_PATH];
readlink("/proc/self/exe", buffer, MAX_PATH);
Bartosz Przybylski
  • 1,628
  • 10
  • 15
  • Thanks @Barter, I have a Windows but it returns path with .exe name, how can i cut this exe name from end of the path? – Roman Oct 14 '12 at 14:09
  • All you need to do is find last \ and put NULL in that place. Or using [`PathRemoveFileSpec`](http://msdn.microsoft.com/en-us/library/windows/desktop/bb773748(v=vs.85).aspx) – Bartosz Przybylski Oct 14 '12 at 14:13
0

There's no good cross-platform solution for this, however, you can do this on all major platforms:

  • on Linux: read the /proc/self/exe special file

char buf[PATH_MAX];
ssize_t len;
if ((len = readlink("/proc/self/exe", buf, bufsize)) != -1) {
    // buf contains the path
} else {
    // error
}
  • on Mac OS X: use the _NSGetExecutablePath() function (from man 3 dyld)

#include <stdint.h>
#include <limits.h>

uint32_t size = PATH_MAX;
char buf[PATH_MAX];
if (_NSGetExecutablePath(buf, &size) != -1) {
    // buf now contains the path
} else {
    // error
}
  • on Windows: call GetModuleFileName() with NULL as the handle.

#include <windows.h>

char buffer[1024];
if (GetModuleFileName(NULL, buffer, sizeof(buffer)) != 0) {
    // buffer contains the path
} else {
    // error
}