Kurlyk
Loading...
Searching...
No Matches
path_utils.hpp
Go to the documentation of this file.
1#pragma once
2#ifndef _KURLYK_UTILS_PATH_UTILS_HPP_INCLUDED
3#define _KURLYK_UTILS_PATH_UTILS_HPP_INCLUDED
4
7
8#if __cplusplus >= 201703L
9#include <filesystem>
10#endif
11
12namespace kurlyk::utils {
13
16 std::string get_exec_dir() {
17# if defined(_WIN32)
18 std::vector<wchar_t> buffer(MAX_PATH);
19 HMODULE hModule = GetModuleHandle(NULL);
20
21 // Пробуем получить путь
22 DWORD size = GetModuleFileNameW(hModule, buffer.data(), buffer.size());
23
24 // Если путь слишком длинный, увеличиваем буфер
25 while (size == buffer.size() && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
26 buffer.resize(buffer.size() * 2); // Увеличиваем буфер в два раза
27 size = GetModuleFileNameW(hModule, buffer.data(), buffer.size());
28 }
29
30 if (size == 0) throw std::runtime_error("Failed to get executable path.");
31 std::wstring exe_path(buffer.begin(), buffer.begin() + size);
32 std::wstring::size_type pos = exe_path.find_last_of(L"\\/");
33 if (pos != std::wstring::npos) {
34 exe_path = exe_path.substr(0, pos);
35 }
36
37# if __cplusplus >= 201703L
38 return std::filesystem::path(exe_path).u8string();
39# else
40 std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
41 return converter.to_bytes(exe_path);
42# endif
43
44# else
45 char result[PATH_MAX];
46 ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
47
48 if (count == -1) throw std::runtime_error("Failed to get executable path.");
49
50 std::string exe_path(result, count);
51
52 // Обрезаем путь до директории (удаляем имя файла, оставляем только путь к папке)
53 size_t pos = exe_path.find_last_of("\\/");
54 if (pos != std::string::npos) {
55 exe_path = exe_path.substr(0, pos);
56 }
57
58 return exe_path;
59# endif
60 }
61
62} // namespace kurlyk::utils
63
64#endif // _KURLYK_UTILS_PATH_UTILS_HPP_INCLUDED
std::string get_exec_dir()
Retrieves the directory of the executable file.