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;
}
相关推荐
WBluuue18 分钟前
Codeforces 1078 Div2(ABCDEF1)
c++·算法
学无止境_永不停歇27 分钟前
十、C++多态
开发语言·c++
鸠摩智首席音效师1 小时前
如何在 Linux 中将文件复制到多个目录 ?
linux·运维·服务器
老歌老听老掉牙1 小时前
QT开发踩坑记:按钮点击一次却触发两次?深入解析信号槽自动连接机制
c++·qt
香蕉你个不拿拿^1 小时前
Linux进程地址空间解析
linux·运维·服务器
橘色的喵1 小时前
现代 C++17 相比 C 的不可替代优势
c语言·c++·现代c++·c++17
人间打气筒(Ada)1 小时前
Linux学习~日志文件参考
linux·运维·服务器·学习·日志·log·问题修复
浅念-1 小时前
C/C++内存管理
c语言·开发语言·c++·经验分享·笔记·学习
回敲代码的猴子2 小时前
2月8日上机
开发语言·c++·算法
xuhe22 小时前
Claude Code配合Astro + GitHub Pages:为 sharelatex-ce 打造现代化的开源项目宣传页
linux·git·docker·github·浏览器·overleaf