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;
}
相关推荐
Bug退散师4 分钟前
多路IO复用[select版TCP服务器与poll版TCP服务器]与常用网络编程函数详解
linux·服务器·c语言·网络·驱动开发·tcp/ip
xiaoye-duck7 分钟前
《Linux系统编程》Linux 系统多线程(一):线程概念(从虚拟地址空间与分页机制到优缺点解析)
linux·线程
国服第二切图仔13 分钟前
05-构建与特性开关
linux·服务器·ubuntu
FREEDOM_X13 分钟前
嵌入式——定时器工作原理
linux·c语言·单片机·嵌入式硬件·ubuntu
Thecozzy44 分钟前
Skill和MCP和Subagent 的选择
linux·人工智能·ubuntu
硬核子牙2 小时前
代码展示大模型的智能
linux·chatgpt·agent
风曦Kisaki2 小时前
# Linux 系统资源查看命令总结(附命令快查表)
linux·运维·服务器
清水白石0082 小时前
Python 类定义阶段自动注册子类:从 `__init_subclass__` 到插件系统实战
linux·前端·python
旖-旎2 小时前
《LeetCode 416 分割等和子集》
c++·算法·leetcode·动态规划·背包问题
jiang_changsheng3 小时前
Conda 的默认环境创建优先级。
linux·windows·python