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;
}
相关推荐
2401_858286112 小时前
OS79.【Linux】POSIX信号量
linux·运维·服务器
孬甭_2 小时前
C++ string类
开发语言·c++
盐焗鹌鹑蛋2 小时前
【C++】C++11:右值引用、移动语义万能引用
c++
CodingPioneer2 小时前
03零刻Pro-LS2K3000-Loongnix 20.7.rc1硬盘分区、格式化、挂载与卸载
linux·运维·服务器·硬盘挂载
LingzhiPi2 小时前
零知ESP32--RC522NFC考勤打卡系统
c++·单片机·嵌入式硬件
ShineWinsu2 小时前
对于Linux:TCPsocket编程基础的解析
linux·网络协议·tcp/ip·面试·笔试·进程·远程指令
dddwjzx3 小时前
嵌入式Linux C应用编程——tslib库的使用
linux·嵌入式
Huangjin007_3 小时前
【Linux 系统篇(三)】入门基础指令详解(三)
linux·服务器
言乐63 小时前
Python实现基本搜索引擎
java·linux·开发语言·python·搜索引擎
小灰灰搞电子3 小时前
C++ boost::range 详解:基于最新版本的现代范围处理指南
开发语言·c++