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;
}
相关推荐
李小白202002024 分钟前
EMMC写入/烧录逻辑
linux·运维·服务器
予枫的编程笔记23 分钟前
【Linux入门篇】Linux入门不踩坑:内核、发行版解析+环境搭建全流程
linux·ubuntu·centos·vmware·xshell·linux入门·linux环境搭建
去码头整点薯条9828 分钟前
python第五次作业
linux·前端·python
Trouvaille ~28 分钟前
【Linux】UDP Socket编程实战(二):网络字典与回调设计
linux·运维·服务器·网络·c++·udp·操作系统
niceffking38 分钟前
linux系统编程-线程概述
linux·运维
明洞日记40 分钟前
【图解软考八股034】深入解析 UML:识别标准建模图示
c++·软件工程·软考·uml·面向对象·架构设计
Bdygsl42 分钟前
Linux(12)—— 文件与文件描述符
linux·运维·服务器
前端玖耀里1 小时前
Linux C/C++ 中系统调用与库函数调用的区别
linux·c语言·c++
艾莉丝努力练剑1 小时前
【Linux:文件】基础IO:文件操作的系统调用和库函数各个接口汇总及代码演示
linux·运维·服务器·c++·人工智能·centos·io
松涛和鸣1 小时前
70、IMX6ULL LED驱动实战
linux·数据库·驱动开发·postgresql·sqlserver