From 01e95de886413c252ee1a419ed0a7c41435847e6 Mon Sep 17 00:00:00 2001 From: Egor Tensin Date: Sun, 18 Oct 2020 03:20:06 +0300 Subject: Process: add get_exe_path() --- src/path.cpp | 5 ++++- src/process.cpp | 26 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/path.cpp b/src/path.cpp index 2c2deda..3df5918 100644 --- a/src/path.cpp +++ b/src/path.cpp @@ -16,8 +16,11 @@ namespace winapi { namespace { std::wstring do_canonicalize(const std::wstring& path) { + BOOST_STATIC_CONSTEXPR std::size_t init_buffer_size = MAX_PATH; + static_assert(init_buffer_size > 0, "init_buffer_size must be positive"); + std::vector buffer; - buffer.resize(MAX_PATH); + buffer.resize(init_buffer_size); while (true) { const auto nch = ::GetFullPathNameW(path.c_str(), buffer.size(), buffer.data(), NULL); diff --git a/src/process.cpp b/src/process.cpp index d3ce3a4..7e3a9e7 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -122,6 +122,32 @@ HMODULE Process::get_exe_module() { return module; } +std::string Process::get_exe_path() { + BOOST_STATIC_CONSTEXPR std::size_t init_buffer_size = MAX_PATH; + static_assert(init_buffer_size > 0, "init_buffer_size must be positive"); + + std::vector buffer; + buffer.resize(init_buffer_size); + + while (true) { + SetLastError(ERROR_SUCCESS); + + const auto nch = ::GetModuleFileNameW(NULL, buffer.data(), buffer.size()); + + if (nch == 0) { + throw error::windows(GetLastError(), "GetModuleFileNameW"); + } + + if (nch == buffer.size() && GetLastError() == ERROR_INSUFFICIENT_BUFFER) { + buffer.resize(2 * buffer.size()); + continue; + } + + buffer.resize(nch); + return narrow(buffer); + } +} + std::string Process::get_resource_string(unsigned int id) { wchar_t* s = nullptr; -- cgit v1.2.3