path_to_executable.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2014 Alec Jacobson <[email protected]>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "path_to_executable.h"
  9. #ifdef __APPLE__
  10. # include <mach-o/dyld.h>
  11. #endif
  12. #if defined(_WIN32)
  13. # include <windows.h>
  14. #else
  15. #include <unistd.h>
  16. #endif
  17. #include <cstdint>
  18. IGL_INLINE std::string igl::path_to_executable()
  19. {
  20. // http://pastebin.com/ffzzxPzi
  21. std::string path;
  22. char buffer[1024];
  23. std::uint32_t size = sizeof(buffer);
  24. #if defined (WIN32)
  25. GetModuleFileName(nullptr,buffer,size);
  26. path = buffer;
  27. #elif defined (__APPLE__)
  28. if(_NSGetExecutablePath(buffer, &size) == 0)
  29. {
  30. path = buffer;
  31. }
  32. #elif defined(UNIX) || defined(unix) || defined(__unix) || defined(__unix__)
  33. int byte_count = readlink("/proc/self/exe", buffer, size);
  34. if (byte_count != -1)
  35. {
  36. path = std::string(buffer, byte_count);
  37. }
  38. #elif defined(__FreeBSD__)
  39. int mib[4];
  40. mib[0] = CTL_KERN;
  41. mib[1] = KERN_PROC;
  42. mib[2] = KERN_PROC_PATHNAME;
  43. mib[3] = -1;
  44. sysctl(mib, 4, buffer, sizeof(buffer), NULL, 0);
  45. path = buffer;
  46. #elif defined(SUNOS)
  47. path = getexecname();
  48. #endif
  49. return path;
  50. }