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;
}
相关推荐
盐焗鹌鹑蛋2 小时前
【C++】多态
java·jvm·c++
AOwhisky2 小时前
Linux(CentOS)系统管理入门笔记(第一期)——从 Multics 到主流发行版
linux·运维·笔记·centos·云计算
从零开始的代码生活_2 小时前
Linux epoll 多路转接详解
linux·运维·网络·后端·tcp/ip·计算机网络·php
渣渣盟3 小时前
Linux软件管理与编辑器命令速查手册
linux·运维·编辑器
无足鸟ICT3 小时前
【RHCA+】扩展正则表达式
linux·正则表达式
会周易的程序员3 小时前
microLog 的 log_reader 架构解析:嵌入式日志检索引擎的设计之道
c++·物联网·架构·日志·iot·aiot
一池秋_3 小时前
ubuntu(linux)完美复刻windows11字体,解决linux字体费眼晴
linux·运维·ubuntu
随风一样自由3 小时前
【WSL+Linux】国内网络连接微软官方服务器(或GitHub)不稳定,导致下载内核或Linux发行版时超时断开如何解决?
linux·服务器·wsl
汉克老师3 小时前
GESP2026年6月认证C++七级( 第一部分选择题(8-15))精讲
c++·dfs·bfs·哈希·二分算法·gesp7级·网格dp
zh_xuan3 小时前
c++ Expected用法
开发语言·c++·expected