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;
}
相关推荐
用户476022022786 分钟前
机器配置免密切root
linux
咔咔咔的14 分钟前
3190. 使所有元素都可以被 3 整除的最少操作数
c++
zzzsde1 小时前
【Linux】基础开发工具(2):vim补充说明&&gcc/g++编译器
linux·运维·服务器
T***16071 小时前
C++在游戏开发中的AI行为树
开发语言·c++
q***65691 小时前
使用Canal将MySQL数据同步到ES(Linux)
linux·mysql·elasticsearch
2301_807583231 小时前
了解python,并编写第一个程序,常见的bug
linux·python
自由生长20242 小时前
为什么C++项目偏爱.cxx扩展名:从MongoDB驱动说起
c++
CSDN_RTKLIB2 小时前
【GNU、GCC、g++、MinGW、MSVC】上
c++·gnu
杨德杰2 小时前
Ubuntu设置VNC远程桌面
linux·运维·ubuntu
b***74882 小时前
C++在系统中的内存对齐
开发语言·c++