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;
}
相关推荐
liudanzhengxi6 分钟前
CRM系统技术文章
linux·服务器·网络·人工智能·新人首发
南境十里·墨染春水8 分钟前
守护进程编程流程
linux·学习
杨校22 分钟前
杨校老师课堂之C++的位运算应用专项训练
开发语言·c++
j7~31 分钟前
【MYSQL】在Centos7和ubuntu22.04环境下安装
数据库·c++·mysql·ubuntu·centos
代码中介商37 分钟前
C++ STL 容器完全指南(三):deque、list 与 map 深度详解
开发语言·c++
eggrall1 小时前
Linux进程信号——像收快递一样理解 Linux 信号
linux·开发语言·c++
灰色人生qwer1 小时前
Python 规则:带默认值的参数必须放在不带默认值的后面
linux·windows·python
‎ദ്ദിᵔ.˛.ᵔ₎1 小时前
c++ 11左值和右值
c++
Hical_W1 小时前
C++ Web 框架性能实测(Benchmark)
c++·开源
嘿嘿嘿x31 小时前
Linux-实践
linux·运维·算法