比如我的程序名 为: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;
}