工具类库系列(二)-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
- 工具类库系列(二)-ExePath
- java工具类系列 (二.StopWatch)
- mybatis系列二:mybatis工具类及其使用
- Profile 工具系列之二: gperftools
- 工具类库系列(一)-StringTool
- 工具类库系列(三)-IniReader
- 工具类库系列(四)-CsvReader
- 工具类库系列(五)-Timer
- 工具类库系列(六)-TimeTool
- 工具类库系列(七)-Logger
- 工具类库系列(八)-WinService
- 工具类库系列(九)-ReflectEnum
- 工具类库系列(十)-Object
- 工具类库系列(十一)-ObjectMap
- 工具类库系列(十二)-ObjectSharedPtrMap
- 工具类库系列(十三)-ObjectSharedPtrMap2
- 工具类库系列(十四)-FileData
- 工具类系列-JavaBean2Map
- 围棋AI连胜人类50场,是时候认真思考如何应对人工智能了
- servlet+重定向+转发+数据传递
- JavaScript调试技巧之console.log()详解
- 常见文件系统,超级块,引导扇区
- JavaScript设计模式——单例模式
- 工具类库系列(二)-ExePath
- metasploit学习笔记之主机探测和端口扫描
- JSP与servlet之间的传值方式
- 设计模式-----命令模式
- 287. Find the Duplicate Number***
- Final Assignment
- layout-入门
- 百度查询复制粘贴: MySQL 中取子串函数 SUBSTR(SUBSTRING)
- 数组字符串那些经典算法:最大子序列和,最长递增子序列,最长公共子串,最长公共子序列,字符串编辑距离,最长不重复子串,最长回文子串