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;
}
相关推荐
-梅1 小时前
linux(番外)线程,锁,条件变量封装;日志与线程池
linux·c语言·前端·c++
S_WEAN1 小时前
【C++】STL - Priority_queue的使用及模拟实现与仿函数
开发语言·c++
2401_858286112 小时前
LKDS8.Linux内核的双向链表代码解析(8) 拼接链表、获取链表首/尾元素的宏、list_for_each系列的安全版本的宏
linux·链表
渴了喝洗衣液2 小时前
第一阶段项目
linux·运维·服务器
俊俊几年的3 小时前
嵌入式 Linux 应用开发:CMake 详解与交叉编译实践
linux·c++·嵌入式·cmake·linux应用开发
蹊黎11 小时前
Linux 进程概念(四):命令行参数与环境变量
linux·运维·服务器
wefg112 小时前
【项目】C++ 基于 Vibe Coding 的 OJ 平台
开发语言·c++
郝学胜-神的一滴19 小时前
Effective STL 条款 07:指针容器销毁前先删除
开发语言·c++·vscode·leetcode·rpc·visual studio
Lucas. Wáng21 小时前
Qt学习之旅
c++·qt
蜗牛一步步往上爬21 小时前
第十一章 构建基本脚本
linux