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;
}
相关推荐
YXXY3131 天前
线程的介绍(四)
linux
kTR2hD1qb1 天前
从 Responses API 到 Chat Completions:一个模型网关的设计复盘
linux·前端
姓刘的哦1 天前
大模型祛魅
linux
小欣加油1 天前
leetcode3751 范围内总波动值I
java·数据结构·c++·算法·leetcode
代码中介商1 天前
C++左值与右值:核心判断法则详解
开发语言·c++
玖玥拾1 天前
C/C++ 基础笔记(七)
c语言·c++
hj2862511 天前
linux下一步学习内容
linux·运维
珊瑚里的鱼1 天前
手撕单例模式中的饿汉模式和懒汉模式,懒汉模式还要再多加一个C++11版本的
开发语言·c++·单例模式
xier_ran1 天前
【infra之路】Linux基础命令与系统排查
linux·运维·服务器
zh路西法1 天前
【Linux 串口通信】基于 C++ 多线程的同步/异步串口实现
linux·运维·c++·python