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;
}
相关推荐
啊我不会诶7 分钟前
CF每日4题(1300-1400)
开发语言·c++·算法
freyazzr17 分钟前
Leetcode刷题 | Day64_图论09_dijkstra算法
数据结构·c++·算法·leetcode·图论
珊瑚里的鱼26 分钟前
【滑动窗口】LeetCode 1004题解 | 最大连续1的个数 Ⅲ
开发语言·c++·笔记·算法·leetcode
独行soc36 分钟前
2025年渗透测试面试题总结-安恒[实习]安全服务工程师(题目+回答)
linux·数据库·安全·web安全·面试·职场和发展·渗透测试
L汐1 小时前
01 CentOS根分区满了扩容
linux·运维·centos
小峰编程1 小时前
Python函数——万字详解
linux·运维·服务器·开发语言·前端·网络·python
yxc_inspire1 小时前
基于Qt的app开发第九天
c++·qt·app
芯眼1 小时前
正点原子STM32新建工程
开发语言·c++·stm32·单片机·软件工程
大筒木老辈子1 小时前
Linux笔记---内核态与用户态
linux·运维·笔记
五花肉村长2 小时前
Linux-进程信号
linux·运维·服务器·开发语言·网络·c++