Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Tested: Windows 7, OSX 10.10, Archlinux
- #include <cstdlib>
- #include <cstdio>
- #include <algorithm>
- #include <string>
- #ifdef _WIN32
- # define WIN32_LEAN_AND_MEAN
- # include <Windows.h>
- #elif defined(__APPLE__)
- # include <mach-o/dyld.h>
- #else
- # include <unistd.h>
- #endif
- static std::string GetCurrentExecutablePath() {
- std::string result(128, '\0');
- #ifdef _WIN32
- std::size_t bufsize;
- while ((bufsize = ::GetModuleFileNameA(NULL, &result[0], result.length())) == result.length()) {
- result.resize(result.length() * 2);
- }
- result.resize(bufsize);
- #elif defined(__APPLE__)
- uint32_t bufsize = static_cast<uint32_t>(result.length());
- if (::_NSGetExecutablePath(&result[0], &bufsize) != 0) {
- result.resize(bufsize);
- ::_NSGetExecutablePath(&result[0], &bufsize);
- }
- #else
- ssize_t bufsize;
- while ((bufsize = ::readlink(
- # ifdef __linux__
- "/proc/self/exe"
- # else
- "/proc/curproc/file"
- # endif
- , &result[0], result.length())) >= static_cast<ssize_t>(result.length())) {
- result.resize(result.length() * 2);
- }
- if (bufsize < 0) {
- result.clear();
- } else {
- result.resize(bufsize);
- }
- #endif
- result.resize(result.rfind(
- #ifdef _WIN32
- '\\'
- #else
- '/'
- #endif
- ) + 1);
- return result;
- }
- int main() {
- std::puts(GetCurrentExecutablePath().c_str());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement