linux c++获取当前程序的运行路径

比如我的程序名 为:aaa

存放路径 是:/homo/code/

我在/home/ccc 目录执行shell文件。shell文件的内容为

powershell 复制代码
#!/bin/bash
/homo/code/aaa

希望 获取的路径是 /homo/code/ 而不是脚本的路径

给出完整接口代码

cpp 复制代码
#include <iostream>
#include <string>
#include <string.h>
#include <unistd.h>

#define MAX_PATH_LEN  256

bool getCurrRunningPath(std::string &currPath)
{
    char path[MAX_PATH_LEN] = {0};
    char *p = NULL;
    ssize_t n = readlink("/proc/self/exe", path, MAX_PATH_LEN);
    if (n > 0) {
        p = strrchr(path, '/');
        *(p + 1) = '\0'; // 去掉最后的程序名称
        currPath.assign(path);
        std::cout << "get current running path:" << path << std::endl;
        return true;
    } else {
        std::cout << "get current running path failed, errno: " << errno << std::endl;
    }

    return false;
}

int main()
{
 std::string curpath;
 getCurrRunningPath(curpath);
 std::cout << "***: " << curpath << std::endl;

 return 0;
}
相关推荐
彩色的黑'''1 小时前
[root@localhost ~]#,Linux系统的命令提示符为啥现在变成-bash-4.2#了,哪里设置的
linux·运维·bash
源远流长jerry2 小时前
Linux 网络发送机制深度解析:从应用到网线
linux·服务器·网络·网络协议·tcp/ip
王老师青少年编程2 小时前
csp信奥赛C++高频考点专项训练之字符串 --【字符串排序】:合并序列
c++·字符串·csp·高频考点·信奥赛·字符串排序·合并序列
南境十里·墨染春水2 小时前
linux学习进展 shell编程
linux·运维·学习
goyeer3 小时前
【ITIL4】32服务实践 - 问题管理(Problem Management)
linux·运维·服务器·企业数字化·it管理·itil·it治理
handler013 小时前
UDP协议与网络通信知识点
c语言·网络·c++·笔记·网络协议·udp
神仙别闹3 小时前
基于QT(C++)实现学生成绩管理系统
数据库·c++·qt
怀旧,3 小时前
【Linux网络编程】8. 网络层协议 IP
linux·网络·tcp/ip
RH2312113 小时前
2026.5.12 Linux
java·linux·数据结构
cen__y4 小时前
Linux11(网络编程)
linux·运维·服务器·c语言·网络·网络协议·tcp/ip