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

Yia*_*128 6 c++

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

这也是最好的方法吗?最好的方法是直接提供文件夹目录的跨平台命令(如果不存在则使用 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 3

在 Mac OS 的支持下:

#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] = '\0';
#endif
}
Run Code Online (Sandbox Code Playgroud)