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;
}
相关推荐
CN-Dust1 分钟前
【C++专题】输出cout例题
开发语言·c++
charlie1145141915 分钟前
嵌入式Linux驱动开发(7) 从虚拟设备到真实硬件 —— LED驱动硬件基础
linux·开发语言·驱动开发·内核·c
Mortalbreeze21 分钟前
软件包管理器yum和编辑器vim详解 —— 附带vim配置链接
linux·服务器
沉默-_-24 分钟前
备战蓝桥杯-哈希
c++·学习·算法·蓝桥杯·哈希算法
Reese_Cool25 分钟前
【STL】蓝桥杯/天梯赛终极杀器!10个C++字符串核心技巧,暴力破解高频考点
开发语言·c++·蓝桥杯·stl
hehelm1 小时前
C++ 模拟实现 AVL 树
开发语言·c++
李日灐1 小时前
< 7 > Linux 开发工具:git 版本控制器 和 cgdb/gdb 调试器
linux·运维·服务器·开发语言·git·调试器·gdb/cgdb
jieyucx1 小时前
Go 语言 switch 条件语句详解
开发语言·c++·golang
青木9601 小时前
前后端开发调试运行技巧
linux·服务器·前端·后端·npm·uv
万法若空1 小时前
C++ <iomanip> 库全方位详解
开发语言·c++