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;
}
相关推荐
光电的一只菜鸡4 小时前
ubuntu之坑(二十)——VMware虚拟机系统无法正常进入如何处理
linux·运维·ubuntu
「QT(C++)开发工程师」5 小时前
C++ 11 常用for循环
开发语言·c++
我还记得那天5 小时前
0 初识C++
开发语言·c++
你住过的屋檐6 小时前
【Nginx】linux上安装nginx
linux·运维·nginx
宵时待雨6 小时前
linux笔记归纳17:传输层协议UDP
linux·笔记·udp
「QT(C++)开发工程师」7 小时前
C++ std::move 详解
开发语言·c++
SCandL1528 小时前
k8s service
linux·容器·kubernetes
会飞的土拨鼠呀9 小时前
Linux的存储使用率应该如何计算
linux·运维·服务器
豆沙沙包?10 小时前
C++~~~set容器、map容器(p57-P69)
开发语言·c++