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;
}
相关推荐
虾..8 小时前
Linux 软硬链接和动静态库
linux·运维·服务器
Evan芙8 小时前
Linux常见的日志服务管理的常见日志服务
linux·运维·服务器
kk哥88999 小时前
C++ 对象 核心介绍
java·jvm·c++
helloworddm9 小时前
WinUI3 主线程不要执行耗时操作的原因
c++
hkhkhkhkh12310 小时前
Linux设备节点基础知识
linux·服务器·驱动开发
无能者狂怒10 小时前
YOLO C++ Onnx Opencv项目配置指南
c++·opencv·yolo
集智飞行10 小时前
c++函数传参的几种推荐方式
开发语言·c++
HZero.chen11 小时前
Linux字符串处理
linux·string
张童瑶11 小时前
Linux SSH隧道代理转发及多层转发
linux·运维·ssh
汪汪队立大功12311 小时前
什么是SELinux
linux