Add util::executable_path()
This commit is contained in:
parent
ffe7afff1f
commit
42f986ce4a
2 changed files with 46 additions and 0 deletions
10
libs/util/include/psemek/util/executable_path.hpp
Normal file
10
libs/util/include/psemek/util/executable_path.hpp
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <filesystem>
|
||||||
|
|
||||||
|
namespace psemek::util
|
||||||
|
{
|
||||||
|
|
||||||
|
std::filesystem::path executable_path();
|
||||||
|
|
||||||
|
}
|
||||||
36
libs/util/source/executable_path.cpp
Normal file
36
libs/util/source/executable_path.cpp
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
#include <psemek/util/executable_path.hpp>
|
||||||
|
#include <psemek/util/to_string.hpp>
|
||||||
|
|
||||||
|
#ifdef WIN32
|
||||||
|
#include <libloaderapi.h>
|
||||||
|
#include <errhandlingapi.h>
|
||||||
|
#include <winerror.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace psemek::util
|
||||||
|
{
|
||||||
|
|
||||||
|
std::filesystem::path executable_path()
|
||||||
|
{
|
||||||
|
#if defined WIN32
|
||||||
|
std::string result(256, '\0');
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
GetModuleFileNameA(NULL, result.data(), result.size());
|
||||||
|
auto error = GetLastError();
|
||||||
|
if (error == ERROR_SUCCESS)
|
||||||
|
break;
|
||||||
|
else if (error == ERROR_INSUFFICIENT_BUFFER)
|
||||||
|
result.resize(result.size() * 2);
|
||||||
|
else
|
||||||
|
throw std::runtime_error(util::to_string("failed to retrieve executable path: ", std::hex, error));
|
||||||
|
}
|
||||||
|
return std::filesystem::path(result);
|
||||||
|
#elif defined __linux__
|
||||||
|
return std::filesystem::canonical("/proc/self/exe");
|
||||||
|
#else
|
||||||
|
throw std::runtime_error("executable_path() is not implemented for this platform");
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
Loading…
Add table
Reference in a new issue