Skip to content

Instantly share code, notes, and snippets.

@Bak-Jin-Hyeong
Last active May 13, 2017 11:46
Show Gist options
  • Save Bak-Jin-Hyeong/03e6e7fdce103ccbad6af69002934870 to your computer and use it in GitHub Desktop.
Save Bak-Jin-Hyeong/03e6e7fdce103ccbad6af69002934870 to your computer and use it in GitHub Desktop.
#ifndef GETEXEMODULEPATH__HPP__
#define GETEXEMODULEPATH__HPP__
#if !defined(_WINDOWS_) && !defined(__AFX_H__)
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif
#include <string>
inline std::wstring GetModuleFullPathImpl(HMODULE moduleHandle, wchar_t module[], bool directoryOnly) {
std::wstring moduleName;
for (int bufferLength = MAX_PATH; bufferLength < (1 << 15) + MAX_PATH;) {
moduleName.resize(bufferLength);
::SetLastError(0);
const auto r = ::GetModuleFileNameW(
moduleHandle, &moduleName[0], bufferLength);
if (ERROR_INSUFFICIENT_BUFFER == ::GetLastError()) {
bufferLength += 256;
}
else {
moduleName.resize(r);
break;
}
}
const auto required =
::GetFullPathNameW(moduleName.c_str(), 0, nullptr, nullptr);
if (required == 0) {
return{};
}
std::wstring result;
result.resize(required + 1);
wchar_t* filePart = nullptr;
auto n = ::GetFullPathNameW(
moduleName.c_str(), required, &result[0], &filePart);
if (n > 0 && filePart && directoryOnly) {
*filePart = '\0';
result.resize(filePart - &result[0]);
}
else {
result.resize(n);
}
return result;
}
inline std::wstring GetExeModuleDirectory()
{
return GetModuleFullPathImpl(nullptr, true);
}
inline std::wstring GetExeModulePath()
{
return GetModuleFullPathImpl(nullptr, false);
}
#endif // #ifndef GETEXEMODULEPATH__HPP__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment