在工程实践中,很多同学非常头疼获取当前应用程序的路径,不像Qt有现成的接口可用。
这里给大家提供一个经过个人实践证明可用的实战代码,请大家自取使用。
#ifdef _WIN32
#include <Windows.h>
extern "C" const IMAGE_DOS_HEADER __ImageBase;
#endif // defined(_WIN32)
#define PATH_MAX 1024
using namespace std;
string exePath(bool isExe)
{
char buffer[PATH_MAX * 2 + 1] = { 0 };
#ifdef _WIN32
int n = GetModuleFileNameA(isExe ? nullptr : (HINSTANCE)&__ImageBase, buffer, sizeof(buffer));
#else
int n = readlink("/proc/self/exe", buffer, sizeof(buffer));
#endif
string filePath;
if (n <= 0)
{
filePath = "./";
}
else
{
filePath = buffer;
}
#ifdef _WIN32
for (auto& ch : filePath)
{
if (ch == '\\')
{
ch = '/';
}
}
#endif
return filePath;
}