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;
}
相关推荐
apcipot_rain5 小时前
C++转Java日记(04)
java·开发语言·c++
WL学习笔记7 小时前
vector模拟实现
c++
2035去旅行8 小时前
bootcmd 详细讲解
linux·嵌入式·arm·soc
陈希1239 小时前
Linux 防火墙配置实战:firewalld、iptables 与云安全组
linux·运维·服务器
蜗牛一步步往上爬9 小时前
第十六章 C++语言在深度学习中的应用
开发语言·c++·深度学习
女神下凡9 小时前
芯参谋(95):嵌入式文件系统_开发指南
linux·服务器·arm开发·驱动开发·设计规范
wo_jack13 小时前
C++ 入门笔记(十六):第16课 vector 模拟实现十问十答 —— 从三指针到迭代器失效
c++·后端·面试·stl·vector
且从容.13 小时前
Ubuntu安装flume
linux·ubuntu·flume
承渊政道13 小时前
Linux网络学习【Reactor反应堆模式】
linux·网络·学习·ubuntu·reactor
D e re k ZH13 小时前
C++ 标准库算法全景指南
数据结构·c++·算法