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;
}
相关推荐
相偎24 分钟前
用观察者模式通知UI刷新数据
c++
曾凡宇先生26 分钟前
openEuler安装jdk,nginx,redis
linux·开发语言·数据库·openeuler
_OP_CHEN26 分钟前
Linux系统编程:(三)基础指令详解(2)
linux·man·more·cat·linux指令·cp·whereis
CoderCodingNo42 分钟前
【GESP】C++四级真题 luogu-B4040 [GESP202409 四级] 黑白方块
开发语言·c++
Lenyiin1 小时前
《 Linux 点滴漫谈: 三 》掌控终端:让 Shell 成为你的系统魔杖
linux·运维·服务器·lenyiin
小欣加油1 小时前
leetcode 143 重排链表
数据结构·c++·算法·leetcode·链表
一匹电信狗1 小时前
【MySQL】数据库表的操作
linux·运维·服务器·数据库·mysql·ubuntu·小程序
撬动未来的支点2 小时前
【Linux】Linux 零拷贝技术全景解读:从内核到硬件的性能优化之道
linux·服务器·性能优化
ajassi20002 小时前
开源 Linux 服务器与中间件(六)服务器--Lighttpd
linux·服务器·开源
给大佬递杯卡布奇诺2 小时前
FFmpeg 基本API avio_open函数内部调用流程分析
c++·ffmpeg·音视频