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;
}
相关推荐
j_xxx404_18 分钟前
Linux:静态链接与动态链接深度解析
linux·运维·服务器·c++·人工智能
_只道当时是寻常1 小时前
【Codex】Ubuntu 安装 Codex CLI 并解决 Clash 代理与账号认证问题
linux·ubuntu·chatgpt
c++之路1 小时前
C++23概述
java·c++·c++23
brucelee1862 小时前
Claude Code 安装教程(Windows / Linux / macOS)
linux·windows·macos
jsons12 小时前
给每台虚拟机设置独立控制台密码
linux·运维·服务器
嵌入式×边缘AI:打怪升级日志3 小时前
全志T113 Tina-SDK 配套工具链开发应用(从Makefile到CMake再到Autotools)
linux
嵌入式×边缘AI:打怪升级日志3 小时前
全志T113嵌入式Linux开发环境搭建(VMware + Ubuntu 18.04)详细步骤
linux·ubuntu
学涯乐码堂主3 小时前
有趣的“打擂台算法”
c++·算法·青少年编程·gesp
云栖梦泽4 小时前
Linux内核与驱动:14.SPI子系统
linux·运维·服务器·c++
Gary Studio4 小时前
安卓HAL C++基础-智能指针
开发语言·c++