snippetcppCritical
How do I get the directory that a program is running from?
Viewed 0 times
programdirectoryhowfromrunningthethatget
Problem
Is there a platform-agnostic and filesystem-agnostic method to obtain the full path of the directory from where a program is running using C/C++? Not to be confused with the current working directory. (Please don't suggest libraries unless they're standard ones like clib or STL.)
(If there's no platform/filesystem-agnostic method, suggestions that work in Windows and Linux for specific filesystems are welcome too.)
(If there's no platform/filesystem-agnostic method, suggestions that work in Windows and Linux for specific filesystems are welcome too.)
Solution
Here's code to get the full path to the executing app:
Variable declarations:
Windows:
Linux:
Variable declarations:
char pBuf[256];
size_t len = sizeof(pBuf);Windows:
int bytes = GetModuleFileName(NULL, pBuf, len);
return bytes ? bytes : -1;Linux:
int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1);
if(bytes >= 0)
pBuf[bytes] = '\0';
return bytes;Code Snippets
char pBuf[256];
size_t len = sizeof(pBuf);int bytes = GetModuleFileName(NULL, pBuf, len);
return bytes ? bytes : -1;int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1);
if(bytes >= 0)
pBuf[bytes] = '\0';
return bytes;Context
Stack Overflow Q#143174, score: 202
Revisions (0)
No revisions yet.