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;
}
相关推荐
Bardb1 分钟前
02__C++的基本语法
c++·qt
程序员JerrySUN17 分钟前
Linux 内核内存管理子系统全面解析与体系构建
java·linux·运维
rui锐rui38 分钟前
大模型模型部署和暴露接口
linux·运维·服务器
孙克旭_1 小时前
day030-Shell自动化编程-函数
linux·运维·自动化
freyazzr1 小时前
C++八股 | Day3 | 智能指针 / 内存管理 / 内存分区 / 内存对齐
开发语言·c++
闻缺陷则喜何志丹1 小时前
【动态规划】B4336 [中山市赛 2023] 永别|普及+
c++·算法·动态规划·洛谷
序属秋秋秋1 小时前
《C++初阶之入门基础》【普通引用 + 常量引用 + 内联函数 + nullptr】
开发语言·c++·笔记
筏.k1 小时前
C++ 网络编程(10) asio处理粘包的简易方式
java·网络·c++
belldeep1 小时前
C++:用 libcurl 发送一封带有附件的邮件
c++·curl·send·email·smpt
虾球xz1 小时前
CppCon 2015 学习:Transducers, from Clojure to C++
开发语言·c++·学习