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;
}
相关推荐
wljy124 分钟前
二、进制状态转换
linux·运维·服务器·c语言·c++
week@eight33 分钟前
Linux - Doris
linux·运维·数据库·mysql
云泽80844 分钟前
笔试算法 -位运算篇(二):从唯一字符到消失数字
c++·算法·位运算
平行云1 小时前
实时云渲染预启动技术解析:UE数字孪生应用的延迟优化机制(二)
linux·unity·ue5·webgl·实时云渲染·云桌面·像素流
繁华落尽,倾城殇?1 小时前
[C++11] : atomic,nullptr,default/delete,enum class
开发语言·c++·c++11·nullptr·atomic·enum class·default/delete
看到代码头都是大的1 小时前
CentOS环境下手动升级openssl、openssh
linux·运维·centos
浮生若城1 小时前
Linux——Ext系列文件系统
linux·运维·服务器
代码村新手1 小时前
C++-二叉搜索树
开发语言·c++
枳实-叶2 小时前
【Linux驱动开发】第16天:按键中断完整实战
linux·运维·驱动开发
智者知已应修善业2 小时前
【51单片机8位数码管动态显示日期小数点风格】2023-11-13
c++·经验分享·笔记·算法·51单片机