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;
}
相关推荐
code_whiter4 分钟前
初阶linux1(常见指令以及权限理解)
linux
平凡的阳阳9 分钟前
千里通Linux盒子搭建FRP全教程:低成本实现内网穿透+代理服务器
linux·frp·内网穿透·代理·socks5·远程ssh
D4c-lovetrain12 分钟前
Linux个人心得25 (mysql⑤)
linux·运维·mysql
菜_小_白19 分钟前
RTP协议收发组件开发
linux·网络·c++
Deitymoon21 分钟前
linux——UDP编程
linux·网络·udp
Amelio_Ming23 分钟前
linux内存管理-页面回收之内核线程 kswapd (二)
linux·服务器
jf加菲猫23 分钟前
第12章 数据可视化
开发语言·c++·qt·ui
wsoz30 分钟前
Leetcode矩阵-day7
c++·算法·leetcode·矩阵
Emberone33 分钟前
C++内存管理+模板初尝试:暴风雨前的尝试
c++
6Hzlia35 分钟前
【Hot 100 刷题计划】 LeetCode 79. 单词搜索 | C++ 标准方向数组 DFS 与回溯
c++·leetcode·深度优先