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;
}
相关推荐
风曦Kisaki5 分钟前
# Linux实战笔记-HIS项目实战Day01:版本控制与Git基础
linux·笔记·git
jsons11 小时前
rocky8内网离线批量补丁(你之前搭建的架构,多台服务器首选,无订阅)
linux·运维·服务器
csdndenglu1 小时前
Easy3D:一个轻量级、易用、高效的C++库,用于处理和渲染3D数据,无复杂要求时可替代VTK
开发语言·c++·图形渲染·3d渲染
阿拉斯攀登1 小时前
SPI 设备驱动开发
linux·驱动开发·嵌入式硬件·linux内核·嵌入式·linux驱动·spi
zhou135284822672 小时前
Windows 配置 WSL (Ubuntu) 环境完整指南
linux·windows·ubuntu
FREEDOM_X2 小时前
Linux 进程间通讯(IPC)——总结
linux·c语言·前端·嵌入式硬件·struts
天空'之城2 小时前
Linux 系统编程 17:零拷贝技术全解
linux·嵌入式·零拷贝技术全解
网络小白不怕黑2 小时前
11.虚拟机模拟路由器实验
linux·运维·服务器·网络
chh5632 小时前
C++--vector
开发语言·c++·学习·算法
Mapleay3 小时前
Linux 内核编程基础
linux·运维·服务器