获取 exe 文件夹路径的最佳方法?
Best way to get exe folder path?
我在另一个应该给你的论坛上找到了这个。但我认为这可能不是最好的方法,而且我认为由于数组未被删除而导致内存泄漏。这是真的吗?
这也是最好的方法吗?最好的方法是直接提供文件夹目录的跨平台命令(如果不存在,请使用 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
}
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 在C++中向零方向近似的最佳方法
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 检测win32服务创建和删除的最佳方法
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 将线程中的数据存储到全局容器的最佳方法?
- 将一系列整数放入类的最佳方法是什么?
- 在派生类中使用基类的私有成员变量的最佳方法
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 比较两个节点坐标的最佳方法是什么?
- 在nodejs中使用本机代码的最佳方法是什么?
- 将 pybind11 绑定标记为已弃用的最佳方法
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- C++中变量混叠的最佳方法
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?