Advertisement
zhangsongcui

Get current executable path

Feb 1st, 2015
361
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. // Tested: Windows 7, OSX 10.10, Archlinux
  2.  
  3.  
  4. #include <cstdlib>
  5. #include <cstdio>
  6. #include <algorithm>
  7. #include <string>
  8.  
  9. #ifdef _WIN32
  10. #   define WIN32_LEAN_AND_MEAN
  11. #   include <Windows.h>
  12. #elif defined(__APPLE__)
  13. #   include <mach-o/dyld.h>
  14. #else
  15. #   include <unistd.h>
  16. #endif
  17.  
  18. static std::string GetCurrentExecutablePath() {
  19.     std::string result(128, '\0');
  20. #ifdef _WIN32
  21.     std::size_t bufsize;
  22.     while ((bufsize = ::GetModuleFileNameA(NULL, &result[0], result.length())) == result.length()) {
  23.         result.resize(result.length() * 2);
  24.     }
  25.     result.resize(bufsize);
  26. #elif defined(__APPLE__)
  27.     uint32_t bufsize = static_cast<uint32_t>(result.length());
  28.     if (::_NSGetExecutablePath(&result[0], &bufsize) != 0) {
  29.         result.resize(bufsize);
  30.         ::_NSGetExecutablePath(&result[0], &bufsize);
  31.     }
  32. #else
  33.     ssize_t bufsize;
  34.     while ((bufsize = ::readlink(
  35. #   ifdef __linux__
  36.                     "/proc/self/exe"
  37. #   else
  38.                     "/proc/curproc/file"
  39. #   endif
  40.                     , &result[0], result.length())) >= static_cast<ssize_t>(result.length())) {
  41.         result.resize(result.length() * 2);
  42.     }
  43.     if (bufsize < 0) {
  44.         result.clear();
  45.     } else {
  46.         result.resize(bufsize);
  47.     }
  48. #endif
  49.  
  50.     result.resize(result.rfind(
  51. #ifdef _WIN32
  52.                     '\\'
  53. #else
  54.                     '/'
  55. #endif
  56.                     ) + 1);
  57.     return result;
  58. }
  59. int main() {
  60.     std::puts(GetCurrentExecutablePath().c_str());
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement