• 工资「喂饱肚子」,副业「养活灵魂」!

  • 欢迎大家交换友链,可在https://www.stubbornhuang.com/申请友情链接进行友链交换申请!

  • 感谢大家访问本站,希望本站的内容可以帮助到大家!

  • 如果觉得本站的内容有帮助,可以考虑打赏博主哦!

  • 本站会放置Google广告用于维持域名以及网站服务器费用。

  • 问题反馈可发送邮件到stubbornhuang@qq.com

  • 本站由于前段时间遭受到大量临时和国外邮箱注册,所以对可注册的邮箱类型进行了限制!

  • 在本站开通年度VIP,无限制下载本站资源和阅读本站文章

  • 计算机图形学与计算几何经典必备书单整理,下载链接可参考:https://www.stubbornhuang.com/1256/

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

C++ 发布于2023-09-07 阅读 1,828次 0次评论 0次点赞 本文共1663个字,阅读需要5分钟。

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

跨平台获取当前可执行程序路径是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;
}

欢迎扫码关注我的微信公众号,及时获取文章更新

微信公众号二维码

本文作者:StubbornHuang

版权声明:本文为站长原创文章,如果转载请注明原文链接!

原文标题:C++ – 跨平台在Windows、Linux系统上获取当前可执行程序路径

原文链接:https://www.stubbornhuang.com/2790/

发布于:2023年09月07日 11:45:54

修改于:2023年09月07日 11:45:54

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

文章末尾
上一篇
CMake - 链接多线程pthread库的几种方式
C++
下一篇
Docker - Linux更换国内镜像源
Linux运维
当前分类随机文章推荐

发表评论

您必须 [ 登录 ] 才能发表留言!

关注我们的公众号

微信公众号