Skip to content

Instantly share code, notes, and snippets.

@MarioLiebisch
Created July 22, 2018 16:18
Show Gist options
  • Save MarioLiebisch/d65d0faae2196f4c50b88884aff38c1d to your computer and use it in GitHub Desktop.
Save MarioLiebisch/d65d0faae2196f4c50b88884aff38c1d to your computer and use it in GitHub Desktop.
Small utility function to get a running program's own executable path. This should work even if it's called using a symbolic link.
std::string getSelf()
{
char buf[1024] = { 0 };
#ifdef WIN32
DWORD ret = GetModuleFileNameA(NULL, buf, sizeof(buf));
if (ret && ret != sizeof(buf)) {
std::string res(buf);
for (auto &c : res)
if (c == '\\')
c = '/';
return res;
}
#else
ssize_t ret = readlink("/proc/self/exe", buf, sizeof(buf));
if (ret && ret != sizeof(buf))
return buf;
#endif
throw std::exception("Couldn't determine executable path.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment