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;
}
相关推荐
咸鱼Doyoung1 小时前
《commander-cpp》单头文件的、链式调用的、自动生成帮助文档的C++命令行参数解析库
c++
Xの哲學1 小时前
Linux SLUB 内存分配器深度剖析: 从设计哲学到实战调试
linux·服务器·网络·算法·边缘计算
橘色的喵1 小时前
嵌入式 ARM Linux 平台高性能无锁异步日志系统设计与实现
linux·arm开发·cache line·ring buffer
2401_876221341 小时前
AtCoder Beginner Contest 439 - D - Kadomatsu Subsequence
c++·算法
何中应1 小时前
linux使用root账户操作提示没有权限
linux·运维·服务器
天上飞的粉红小猪1 小时前
网络基础概念
linux·服务器·网络·c++
嵌入式进阶行者1 小时前
【算法】从数组中选取两个符合一定条件的数的算法与实例:华为OD机考双机位A卷 - 跳房子I
数据结构·c++·算法·链表
qq_5470261791 小时前
Shell 高级用法
linux
Hello_wshuo1 小时前
记RP2040使用Arduino+platformio开发配置
linux·嵌入式硬件·arduino
im_AMBER2 小时前
Leetcode 94 合并零之间的节点
数据结构·c++·笔记·学习·算法·leetcode