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;
}
相关推荐
澈2072 小时前
C++并查集:高效解决连通性问题
java·c++·算法
郝学胜-神的一滴4 小时前
Qt 入门 01-01:从零基础到商业级客户端实战
开发语言·c++·qt·程序人生·软件构建
宏笋4 小时前
C++ thread的detach()方法详解
c++
旖-旎4 小时前
深搜练习(单词搜索)(12)
c++·算法·深度优先·力扣
IT大白鼠4 小时前
Linux进程与计划任务管理:技术详解与实战指南
linux·运维·服务器
拾贰_C4 小时前
【Ubuntu | 公共工作站 | mysql 】 MySQL残留物残留数据
linux·mysql·ubuntu
Ujimatsu5 小时前
虚拟机安装Ubuntu 26.04.x服务器版(命令行版)(2026.5)
linux·windows·ubuntu
大卡片5 小时前
C++的基础知识点
开发语言·c++
米罗篮5 小时前
DSU并查集 & 拓展欧几里得-逆元
c++·经验分享·笔记·算法·青少年编程
hweiyu005 小时前
Linux命令:arptables
linux·运维