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;
}
相关推荐
~黄夫人~26 分钟前
Kubernetes Pod 初始化容器(InitContainer)起不来的排错思路
linux·运维·服务器
明洞日记30 分钟前
【CUDA手册004】一个典型算子的 CUDA 化完整流程
c++·图像处理·算法·ai·图形渲染·gpu·cuda
燃犀知不可乎骤得41 分钟前
MFC学习记录
c++·学习·mfc
运维有小邓@42 分钟前
如何在 Linux 中查看系统日志消息
linux·运维·服务器
星火开发设计1 小时前
C++ 运算符全解析:算术、关系、逻辑与位运算
java·开发语言·c++·学习·位运算·知识·操作符
Emilin Amy1 小时前
【C++】【STL算法】那些STL算法替代的循环
开发语言·c++·算法·ros1/2
天边一坨浮云1 小时前
Ubuntu(PC)遇到的各种问题-EXT4-fs(vdb): VFS: Can‘t find ext4 filesystem
linux·ubuntu
天赐学c语言1 小时前
1.16 - 二叉树的中序遍历 && 动态多态的实现原理
数据结构·c++·算法·leecode
fpcc1 小时前
跟我学C++中级篇—std::is_swappable手动实现
c++
卜锦元1 小时前
EchoChat搭建自己的音视频会议系统01-准备工作
c++·golang·uni-app·node.js·音视频