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 分钟前
`kubectl top nodes` 或 `kubectl top pods` 返回 `metrics not available yet` 的排查、解决
linux
小欣加油9 分钟前
leetcode 174 地下城游戏
c++·算法·leetcode·职场和发展·动态规划
Two_brushes.17 分钟前
Cmake中寻库文件的路径
开发语言·c++·cmake
良木生香23 分钟前
【C语言进阶】文件操作的相关详解(1):
c语言·数据结构·c++
Larry_Yanan23 分钟前
Qt安卓开发(三)双摄像头内嵌布局
android·开发语言·c++·qt·ui
东皇太星34 分钟前
linux 内存管理详解
linux·运维·服务器
玖釉-34 分钟前
[Vulkan 学习之路] 01 - 迈入高性能图形开发的大门 (Windows 环境搭建)
c++·windows·图形渲染
JY.yuyu39 分钟前
Linux计划任务进程
linux·运维·服务器
single-life39 分钟前
Linux 下 部署es+nebula(附带内网部署方式)
linux·运维·elasticsearch·nebula
ICT董老师1 小时前
kubernetes中operator与helm有什么区别?部署mysql集群是选择operator部署还是helm chart部署?
linux·运维·mysql·云原生·容器·kubernetes