C++ - 跨平台在Windows、Linux系统上获取当前可执行程序路径

本文介绍了如何在C++中创建PathUtils工具类,实现在Windows和Linux系统下获取当前可执行程序路径的功能,包括Windows下的GetSelfModuleHandle方法和Linux下的readlink方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 C++跨平台在Windows、Linux系统上获取当前可执行程序路径

跨平台获取当前可执行程序路径是C++跨平台项目中会经常使用的功能,我将这个功能简单的封装成了一个PathUtils工具类,在该类中通过GetCurrentProgramDirectory静态函数获取当前可执行程序路径,下面贴出了功能实现代码。

path_utils.h

#ifndef _PATH_UTILS_H_
#define _PATH_UTILS_H_

#include <string>

class PathUtils
{
public:
	// 得到当前程序执行路径
	static std::string GetCurrentProgramDirectory();
};

#endif // !_PATH_UTILS_H_

path_utils.cpp

#include "path_utils.h"

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)

#include<Windows.h>

#elif defined(linux) || defined(__linux)

#include <string.h>
#include <unistd.h>
#include <dlfcn.h>

#endif // WINDOWS

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
static HMODULE GetSelfModuleHandle()
{
	MEMORY_BASIC_INFORMATION mbi;
	return (
		(::VirtualQuery(GetSelfModuleHandle, &mbi, sizeof(mbi)) != 0)
		? (HMODULE)mbi.AllocationBase : NULL
		);
}

std::string PathUtils::GetCurrentProgramDirectory()
{
	std::string strCurrentPath = "";
	char curDirector[260] = { 0 };
	GetModuleFileName(GetSelfModuleHandle(), curDirector, 260);
	strCurrentPath = curDirector;

	size_t nameStart = strCurrentPath.rfind("\\");
	strCurrentPath = strCurrentPath.substr(0, nameStart + 1);
	return strCurrentPath;
}

#elif defined(linux) || defined(__linux)
std::string PathUtils::GetCurrentProgramDirectory()
{
	std::string strCurrentPath = "";
	char szCurWorkPath[256];
	memset(szCurWorkPath, '\0', 256);
	int nRet = readlink("/proc/self/exe", szCurWorkPath, 256);
	if (nRet > 256 || nRet < 0)
	{
		return strCurrentPath;
	}

	for (int i = nRet; i > 0; i--)
	{
		if (szCurWorkPath[i] == '/' || szCurWorkPath[i] == '\\')
		{
			szCurWorkPath[i] = '\0';
			break;
		}
	}

	strCurrentPath = szCurWorkPath;

	return strCurrentPath;
}
#endif

测试代码

#include <iostream>
#include "path_utils.h"

int main()
{
	std::cout << "Path : " << PathUtils::GetCurrentProgramDirectory() << std::endl;
	return 0;
}

如果有兴趣可以访问我的个人博客:https://www.stubbornhuang.com/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HW140701

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值