49 lines
1.3 KiB
C++
49 lines
1.3 KiB
C++
//
|
|
// Created by shell on 2025/12/4.
|
|
//
|
|
|
|
#include "util/application_path.hpp"
|
|
#include <stdexcept>
|
|
#include <vector>
|
|
#ifdef _WIN32
|
|
#include <windows.h>
|
|
#elif __linux__
|
|
#include <unistd.h>
|
|
#else
|
|
#error "Getting application path operation is only supported on Windows or Linux"
|
|
#endif
|
|
|
|
namespace shell::util {
|
|
#ifdef _WIN32
|
|
std::filesystem::path ApplicationPath::get() {
|
|
std::wstring path(20, L'\0');
|
|
while (true) {
|
|
const DWORD len = GetModuleFileNameW(nullptr, &path[0], path.size());
|
|
if (len == 0) {
|
|
throw std::runtime_error("GetModuleFileName() failed");
|
|
}
|
|
if (len < path.size()) {
|
|
path.resize(len);
|
|
return std::filesystem::path{path};
|
|
}
|
|
path.resize(path.size() * 2);
|
|
}
|
|
}
|
|
#elif __linux__
|
|
std::filesystem::path ApplicationPath::get() {
|
|
std::vector<char> buffer(256);
|
|
while (true) {
|
|
const size_t len = readlink("/proc/self/exe", buffer.data(), buffer.size());
|
|
if (len == -1) {
|
|
throw std::runtime_error("failed to read /proc/self/exe");
|
|
}
|
|
if (len < buffer.size()) {
|
|
return std::filesystem::path{std::string(buffer.data(), len)};
|
|
}
|
|
|
|
buffer.reserve(buffer.size() * 2);
|
|
}
|
|
}
|
|
#endif
|
|
}
|