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;
}
相关推荐
一个人旅程~2 小时前
Linux系统如何分区更合适?
linux·经验分享·电脑
南境十里·墨染春水7 小时前
C++传记(面向对象)虚析构函数 纯虚函数 抽象类 final、override关键字
开发语言·c++·笔记·算法
2301_797172757 小时前
基于C++的游戏引擎开发
开发语言·c++·算法
zfxwasaboy7 小时前
Linux宏clamp(val, lo, hi)的作用
linux·运维·服务器
比昨天多敲两行8 小时前
C++ 二叉搜索树
开发语言·c++·算法
Season4508 小时前
C++11之正则表达式使用指南--[正则表达式介绍]|[regex的常用函数等介绍]
c++·算法·正则表达式
问好眼9 小时前
《算法竞赛进阶指南》0x04 二分-1.最佳牛围栏
数据结构·c++·算法·二分·信息学奥赛
我爱学习好爱好爱9 小时前
Ansible 常用模块详解:lineinfile、replace、get_url实战
linux·python·ansible
海海不瞌睡(捏捏王子)9 小时前
C++ 知识点概要
开发语言·c++
吴声子夜歌10 小时前
TypeScript——基础类型(三)
java·linux·typescript