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;
}
相关推荐
迷途之人不知返3 小时前
【文件系统】-4-软硬连接
linux
hetao17338375 小时前
2026-10-22~23 hetao1733837 的刷题记录
c++·算法
1234567890@world5 小时前
正点原子 ATK-DLRK3568 嵌入式Linux系统开发手册V1.3 详细总结
linux·stm32·单片机
sun_weitao5 小时前
极简版 MCP 工具实现方案
java·linux·服务器
王老师青少年编程6 小时前
2025年6月GESP真题及题解(C++三级): 选择题和判断题(题解)
c++·真题·gesp·答案·csp·三级·信奥赛
卡卡~~7 小时前
“101计划”核心课程实践教材《数据实验结构指导-C++语言版》题目集
开发语言·c++·学习·算法
爱和冰阔落7 小时前
【Linux】线程安全进阶:单例模式、可重入函数与死锁排查
linux·运维·安全·单例模式
先知后行。7 小时前
pimpl
linux
lengxuenong8 小时前
树状数组 · 信息学学习手册1-求和3个模板
c++·学习·算法·青少年编程
q27551300428 小时前
AS8132 DP转HDMI 4K60(420)被动式 国产性价比AS方案
linux·算法·硬件架构·dash