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;
}
相关推荐
Maggie_ssss_supp1 分钟前
Linux-MySQL权限管理
linux·运维·mysql
石像鬼₧魂石3 分钟前
Kali Linux 内网渗透:深度工程实施手册
linux·运维·服务器
Frank_refuel15 分钟前
C++之继承
开发语言·c++
哪有时间简史42 分钟前
C++程序设计
c++
%xiao Q1 小时前
GESP C++四级-216
java·开发语言·c++
LXY_BUAA1 小时前
《source insight》添加对.s文件的支持
linux
tianyuanwo1 小时前
深入浅出SWIG:从C/C++到Python的无缝桥梁
c语言·c++·python·swig
fai厅的秃头姐!1 小时前
01-python基础-day02Linux基础
linux
好评1241 小时前
git常见操作及问题
linux·git
不会代码的小猴2 小时前
Linux环境编程第一天笔记
linux·笔记