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;
}
相关推荐
朱包林7 小时前
Python基础
linux·开发语言·ide·python·visualstudio·github·visual studio
xiaoye-duck7 小时前
《算法题讲解指南:递归,搜索与回溯算法--递归》--3.反转链表,4.两两交换链表中的节点,5.快速幂
数据结构·c++·算法·递归
山栀shanzhi7 小时前
归并排序(Merge Sort)原理与实现
数据结构·c++·算法·排序算法
Trouvaille ~7 小时前
【递归、搜索与回溯】专题(七):FloodFill 算法——勇往直前的洪水灌溉
c++·算法·leetcode·青少年编程·面试·蓝桥杯·递归搜索回溯
biubiubiu07068 小时前
Linux / Ubuntu systemd 服务使用说明
linux·运维·ubuntu
MaximusCoder8 小时前
等保测评命令——Anolis Linux
linux·运维·服务器·网络·经验分享·安全·php
zhooyu8 小时前
二维坐标转三维坐标的实现原理
c++·3d·opengl
zhojiew8 小时前
为agent实现渐进式Skills能力的思考和实践
linux·python·算法
10Eugene9 小时前
C++/Qt自制八股文
java·开发语言·c++
相思难忘成疾9 小时前
《RHEL9虚拟机部署及SSH远程登录实践手册》
linux·运维·ssh·虚拟机