工具类库系列(二)-ExePath

来源:互联网 发布:好用的自动铅笔 知乎 编辑:程序博客网 时间:2024/05/21 02:35

第二个工具类: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 UNICODEwchar_t wscFilePath[MAX_PATH + 1] = { 0 };::GetModuleFileName(NULL, wscFilePath, MAX_PATH + 1);filePath = StringTool::WcStrToMbStr(wscFilePath, L"chs");#else // UNICODEchar mbsFilePath[MAX_PATH + 1];::GetModuleFileName(NULL, mbsFilePath, MAX_PATH + 1);filePath = mbsFilePath;#endif // UNICODEfilePath = StringTool::ReplaceAll(filePath, "\\", "/");filePath = filePath.substr(0, filePath.rfind("/"));#else // WIN32char 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 // WIN32return filePath;}std::string GetExePathAndName(){std::string filePath = "";#ifdef WIN32#ifdef UNICODEwchar_t wscFilePath[MAX_PATH + 1] = { 0 };::GetModuleFileName(NULL, wscFilePath, MAX_PATH + 1);filePath = StringTool::WcStrToMbStr(wscFilePath, L"chs");#else // UNICODEchar mbsFilePath[MAX_PATH + 1];::GetModuleFileName(NULL, mbsFilePath, MAX_PATH + 1);filePath = mbsFilePath;#endif // UNICODEfilePath = StringTool::ReplaceAll(filePath, "\\", "/");#else // WIN32char 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 // WIN32return filePath;}}}


0 0
原创粉丝点击