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;
}
相关推荐
游戏23人生2 分钟前
QT linux下 虚拟键盘使用及注意事项
linux·qt·计算机外设
AAA.建材批发刘哥8 分钟前
03--C++ 类和对象中篇
linux·c语言·开发语言·c++·经验分享
softshow102631 分钟前
使用 Windows 子系统 WSL 安装 Ubuntu 22.04
linux·windows·ubuntu
wadesir32 分钟前
简易制作LinuxShell完全指南(深入解析原理、设计与实践步骤)
linux·运维·服务器
峥无1 小时前
《二叉搜索树:动态数据管理的利器,平衡树的基石》
开发语言·c++·二叉搜索树
CoderCodingNo1 小时前
【GESP】C++五级真题(数论, 贪心思想考点) luogu-B4070 [GESP202412 五级] 奇妙数字
开发语言·c++·算法
水天需0101 小时前
HISTFILE 介绍
linux
CreasyChan2 小时前
VirtualBox 安装 CentOS 7.2
linux·运维·centos
AAA.建材批发刘哥2 小时前
04--C++ 类和对象下篇
linux·c++·经验分享·青少年编程
stolentime2 小时前
洛谷P4417 [COCI 2006/2007 #2] STOL 题解
c++·coci