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 分钟前
GESP2026年9月认证C++五级( 第三部分编程题(1、哥德巴赫猜想))精讲
c++·gesp·小学生·学c++编程
小灰灰搞电子31 分钟前
C++ final 关键字详解:从虚函数到类继承的完整指南
c++·final
weixin_307779131 小时前
C++代码实现MATLAB中的pade函数功能
开发语言·c++·算法·matlab
神仙别闹1 小时前
基于C++实现的(控制台)学校开课查询系统
开发语言·c++
Dylan的码园2 小时前
A+B问题 进制处理【逻辑控制 运算符】
c++·算法
GeW2 小时前
制造强国底座:Linux与数据库驱动的新型工业基础设施
linux
xiaoye-duck2 小时前
《Linux 网络编程》深入理解 IO 多路复用:select 函数详解与 Echo 服务实战
linux·网络
hetao17338372 小时前
2026-09-27~28 hetao1733837 的刷题记录
c++·算法
Tairitsu_H2 小时前
[Linux系统] 命令行参数 | 环境变量 | 程序地址空间
linux·环境变量·命令行参数·程序地址空间
2601_962218612 小时前
C++的几种编译器的实现
开发语言·c++