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;
}
相关推荐
大闲在人19 分钟前
C、C++区别还是蛮大的
c语言·开发语言·c++
Codefengfeng1 小时前
CTF工具篇
linux·运维·服务器
掘根2 小时前
【C++STL】平衡二叉树(AVL树)
开发语言·数据结构·c++
上海合宙LuatOS2 小时前
LuatOS核心库API——【i2c】I2C 操作
linux·运维·单片机·嵌入式硬件·物联网·计算机外设·硬件工程
hetao17338372 小时前
2026-02-13~16 hetao1733837 的刷题记录
c++·算法
浅念-3 小时前
C++ string类
开发语言·c++·经验分享·笔记·学习
一文解千机4 小时前
wine 优化配置及显卡加速,完美运行Electron 编译的程序(新榜小豆芽、作家助手、小V猫等)
linux·ubuntu·electron·wine·wine优化配置·wine显卡加速·wine大型游戏
寻星探路4 小时前
【前端基础】HTML + CSS + JavaScript 快速入门(三):JS 与 jQuery 实战
java·前端·javascript·css·c++·ai·html
忘梓.5 小时前
解锁动态规划的奥秘:从零到精通的创新思维解析(10)
c++·算法·动态规划·代理模式