第二个工具类:ExePath
其实不是一个类了,就是一个全局函数,用来获取exe的当前路径
项目中很多比如读取config,读取资源,生成log,都需要exe的当前路径作为参考
这个功能在windows/linux下有不同的实现方式:
windows下面主要使用GetModuleFileName
linux下面主要使用readlink
用到了上一篇的StringTool
上代码:
ExePath.h
#ifndef __ExePath_h__
#define __ExePath_h__
#include <string>
namespace common{
namespace tool{
std::string GetExePath();
std::string GetExePathAndName();
}
}
#endif
ExePath.cpp
#ifdef WIN32
#include <windows.h> // for GetModuleFileName
#else
#include <unistd.h> // for readlink
#include <limits.h> // for PATH_MAX
#endif
#include "StringTool.h"
namespace common{
namespace tool{
std::string GetExePath()
{
std::string filePath = "";
#ifdef WIN32
#ifdef UNICODE
wchar_t wscFilePath[MAX_PATH + 1] = { 0 };
::GetModuleFileName(NULL, wscFilePath, MAX_PATH + 1);
filePath = StringTool::WcStrToMbStr(wscFilePath, L"chs");
#else // UNICODE
char mbsFilePath[MAX_PATH + 1];
::GetModuleFileName(NULL, mbsFilePath, MAX_PATH + 1);
filePath = mbsFilePath;
#endif // UNICODE
filePath = StringTool::ReplaceAll(filePath, "\\", "/");
filePath = filePath.substr(0, filePath.rfind("/"));
#else // WIN32
char strFilePath[PATH_MAX] = {0};
int n = readlink("/proc/self/exe", strFilePath, PATH_MAX);
if(n > 0 && n < sizeof(strFilePath))
{
filePath = strFilePath;
filePath = StringTool::ReplaceAll(filePath, "\\", "/");
filePath = filePath.substr(0, filePath.rfind("/"));
}
#endif // WIN32
return filePath;
}
std::string GetExePathAndName()
{
std::string filePath = "";
#ifdef WIN32
#ifdef UNICODE
wchar_t wscFilePath[MAX_PATH + 1] = { 0 };
::GetModuleFileName(NULL, wscFilePath, MAX_PATH + 1);
filePath = StringTool::WcStrToMbStr(wscFilePath, L"chs");
#else // UNICODE
char mbsFilePath[MAX_PATH + 1];
::GetModuleFileName(NULL, mbsFilePath, MAX_PATH + 1);
filePath = mbsFilePath;
#endif // UNICODE
filePath = StringTool::ReplaceAll(filePath, "\\", "/");
#else // WIN32
char strFilePath[PATH_MAX] = { 0 };
int n = readlink("/proc/self/exe", strFilePath, PATH_MAX);
if (n > 0 && n < sizeof(strFilePath))
{
filePath = strFilePath;
filePath = StringTool::ReplaceAll(filePath, "\\", "/");
}
#endif // WIN32
return filePath;
}
}
}