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;
}
相关推荐
汉克老师40 分钟前
GESP2024年6月认证C++二级( 第一部分选择题(9-15))
c++·循环结构·分支结构·gesp二级·gesp2级·求余数
王老师青少年编程2 小时前
csp信奥赛c++高频考点假期集训(分模块进阶)
数据结构·c++·算法·csp·高频考点·信奥赛·集训
czxyvX2 小时前
007-Linux进程概念及周边知识
linux
王老师青少年编程3 小时前
2020年信奥赛C++提高组csp-s初赛真题及答案解析(选择题1-5)
c++·题解·真题·初赛·信奥赛·csp-s·提高组
Eternity∞3 小时前
Linux系统下,C语言基础
linux·c语言·开发语言
feng68_4 小时前
HAProxy算法实践
linux·运维·haproxy
plus4s4 小时前
2月18日(82-84题)
c++·算法·动态规划
wangluoqi5 小时前
c++ 树上问题 小总结
开发语言·c++
吹牛不交税5 小时前
在vmware中右键SSH连接虚拟机报错Could not resolve hostname
linux·服务器·ssh
不梦闲人6 小时前
15 面向对象程序设计
c++