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;
}
相关推荐
zh_xuan11 分钟前
c++ string_view
开发语言·c++
Ruiery16 分钟前
Linux 6.6内核 PCIe 深度解析(九):复位机制 — 从 FLR 到 Secondary Bus Reset 的降级链
linux·运维·服务器
FFZero122 分钟前
[mpv架构] (4) demux 线程到底在“预读“什么?
c++·架构·音视频·多媒体
学烹饪的小胡桃29 分钟前
WGCLOUD支持哪些告警方式
linux·运维·服务器·网络·安全
西西弗Sisyphus29 分钟前
C++ 实现 替代 OpenCV resize INTER_LINEAR 的一种方式
c++·opencv
wabs66633 分钟前
关于二叉树【力扣107.二叉树的层序遍历II的思考】
数据结构·c++·算法·leetcode·二叉树·层序遍历
galaxy_strive1 小时前
Qt C++插件化编写项目(1)
开发语言·c++·qt
墨有6661 小时前
#Linux系统命令行操作指南
linux
见叶之秋1 小时前
【C++】C++ 核心进阶(一):泛型编程基石 —— 模板初阶与 STL 体系开篇
开发语言·c++
做运维的阿瑞1 小时前
Linux ELF 文件
linux·运维·服务器