获取 exe 文件夹路径的最佳方法?

Best way to get exe folder path?

本文关键字:最佳 方法 路径 exe 文件夹 获取      更新时间:2023-10-16

我在另一个应该给你的论坛上找到了这个。但我认为这可能不是最好的方法,而且我认为由于数组未被删除而导致内存泄漏。这是真的吗?

这也是最好的方法吗?最好的方法是直接提供文件夹目录的跨平台命令(如果不存在,请使用 Windows(。

std::string ExePath() 
{
using namespace std;
char buffer[MAX_PATH];
GetModuleFileName(NULL, buffer, MAX_PATH);
string::size_type pos = string(buffer).find_last_of("\/");
if (pos == string::npos)
{
return "";
}
else 
{
return string(buffer).substr(0, pos);
}
}

在 macos 支持下:

#include <filesystem>
#ifdef _WIN32
#include <windows.h>
#elif __APPLE__
#include <mach-o/dyld.h>
#include <climits>
#elif
#include <unistd.h>
#endif
std::filesystem::path GetExeDirectory() {
#ifdef _WIN32
// Windows specific
wchar_t szPath[MAX_PATH];
GetModuleFileNameW( NULL, szPath, MAX_PATH );
#elif __APPLE__
char szPath[PATH_MAX];
uint32_t bufsize = PATH_MAX;
if (!_NSGetExecutablePath(szPath, &bufsize))
return std::filesystem::path{szPath}.parent_path() / ""; // to finish the folder path with (back)slash
return {};  // some error
#else
// Linux specific
char szPath[PATH_MAX];
ssize_t count = readlink( "/proc/self/exe", szPath, PATH_MAX );
if( count < 0 || count >= PATH_MAX )
return {}; // some error
szPath[count] = '';
#endif
}

您的代码中没有内存泄漏,但它存在一些问题:

  • 它是特定于Windows的,
  • 它适用于本地代码页,不支持任意 Unicode 文件名。

不幸的是,仅使用C++库没有完成此任务的标准方法,但这里有一个代码可以在Windows和Linux上运行,并且也支持Unicode路径。此外,它还利用了 C++17std::filesystem库:

#include <filesystem>
#ifdef _WIN32
#include <windows.h>
#elif
#include <unistd.h>
#endif
std::filesystem::path GetExeDirectory()
{
#ifdef _WIN32
// Windows specific
wchar_t szPath[MAX_PATH];
GetModuleFileNameW( NULL, szPath, MAX_PATH );
#else
// Linux specific
char szPath[PATH_MAX];
ssize_t count = readlink( "/proc/self/exe", szPath, PATH_MAX );
if( count < 0 || count >= PATH_MAX )
return {}; // some error
szPath[count] = '';
#endif
return std::filesystem::path{ szPath }.parent_path() / ""; // to finish the folder path with (back)slash
}