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;
}
相关推荐
hi_ro_a8 分钟前
基于正倒排索引的boost搜索引擎
linux·c++·搜索引擎·项目
神仙别闹19 分钟前
基于 C++ MFC 实现的个人通讯录管理系统
c++
GG-_-Bond25 分钟前
9.1kv存储持久化模拟面试
linux·c语言·数据结构·c++
Dola_Zou1 小时前
Linux工控机核心算法防逆向与自动化加固方案
linux·自动化·软件加密
欧米欧1 小时前
解析Linux从umask位运算到粘滞位
linux
郝学胜-神的一滴1 小时前
C++20模板元编程 04:变量模板 别名模板与模板Lambda实战
服务器·开发语言·数据结构·c++·程序人生
江屿风2 小时前
【Linux系统】【Linux进程终止等待详解与程序替换机制初体验】流食般投喂
linux·运维·笔记·系统架构·centos·unix
螺蛳粉 螺蛳粉2 小时前
CentOS 7.9 自建 Yum 源服务器搭建指南
linux·服务器·centos
qq_344920562 小时前
Qt事件过滤器
开发语言·c++·qt
码匠许师傅2 小时前
【C++三方组件】fmt:C++字符串格式化的前世今生
c++