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;
}
相关推荐
aaaweiaaaaaa20 分钟前
蓝桥杯c ++笔记(含算法 贪心+动态规划+dp+进制转化+便利等)
c语言·数据结构·c++·算法·贪心算法·蓝桥杯·动态规划
大大大大肉包31 分钟前
私有化部署DeepSeek
linux·运维·服务器
xyd陈宇阳36 分钟前
Linux 入门五:Makefile—— 从手动编译到工程自动化的蜕变
linux·运维·服务器·makefile
FreeLikeTheWind.39 分钟前
Qt 开发时可以在函数内引用的头文件
开发语言·c++·qt
说码解字41 分钟前
C++ 的右值引用和移动语义
c++
h^hh1 小时前
pipe匿名管道实操(Linux)
数据结构·c++·算法
岁ovo寒1 小时前
【无标题】
c++
its_a_win2 小时前
蓝桥杯 2023省B 飞机降落 dfs
c++·算法·蓝桥杯
脑斧猴3 小时前
Linux中进程
linux·服务器·c++
Brandon汐3 小时前
Linux文件传输:让数据飞起来!
linux·运维·网络