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;
}
相关推荐
tokepson18 分钟前
香橙派AI Pro个人云平台 - 从零搭建全记录
linux·服务器·技术·记录
无限进步_21 分钟前
C语言实现贪吃蛇游戏详解
c语言·开发语言·数据结构·c++·后端·算法·游戏
CHANG_THE_WORLD25 分钟前
C++ vs Python 参数传递方式对比
java·c++·python
fengyehongWorld1 小时前
Linux wget命令
linux
ULTRA??1 小时前
C++实现右折叠
开发语言·c++
handsomezqh1 小时前
洛谷U611548 助教的比拼
c++·算法
小李小李快乐不已1 小时前
图论理论基础(4)
c++·算法·图论·迭代加深
崇山峻岭之间1 小时前
C++ Prime Plus 学习笔记025
c++·笔记·学习
fpcc1 小时前
跟我学C++中级篇——Linux系统信号分析
linux
bkspiderx1 小时前
C++操作符优先级与结合性全解析
c++·思维导图·操作符优先级·结合性