工具类库系列(二)-ExePath

第二个工具类: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;
		}

	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值