C / C ++ – 可执行路径

我想获得当前可执行文件的文件路径,但最后没有可执行文件名。

我正在使用:

char path[1024]; uint32_t size = sizeof(path); if (_NSGetExecutablePath(path, &size) == 0) printf("executable path is %s\n", path); else printf("buffer too small; need size %u\n", size); 

它可以工作,但最后会添加可执行文件名。

dirname(path); 在获取路径后,应该返回没有可执行文件的路径,即在Unix系统上,对于Windows,你可以做一些strcpy / strcat魔法。

对于dirname,您需要包含#include

使用dirname

Ubuntu的最佳解决方案!!

 std::string getpath() { char buf[PATH_MAX + 1]; if (readlink("/proc/self/exe", buf, sizeof(buf) - 1) == -1) throw std::string("readlink() failed"); std::string str(buf); return str.substr(0, str.rfind('/')); } int main() { std::cout << "This program resides in " << getpath() << std::endl; return 0; } 
 char* program_name = dirname(path); 

对于Linux:
执行系统命令的function

 int syscommand(string aCommand, string & result) { FILE * f; if ( !(f = popen( aCommand.c_str(), "r" )) ) { cout << "Can not open file" << endl; return NEGATIVE_ANSWER; } const int BUFSIZE = 4096; char buf[ BUFSIZE ]; if (fgets(buf,BUFSIZE,f)!=NULL) { result = buf; } pclose( f ); return POSITIVE_ANSWER; } 

然后我们得到应用名称

 string getBundleName () { pid_t procpid = getpid(); stringstream toCom; toCom << "cat /proc/" << procpid << "/comm"; string fRes=""; syscommand(toCom.str(),fRes); size_t last_pos = fRes.find_last_not_of(" \n\r\t") + 1; if (last_pos != string::npos) { fRes.erase(last_pos); } return fRes; } 

然后我们提取应用路径

  string getBundlePath () { pid_t procpid = getpid(); string appName = getBundleName(); stringstream command; command << "readlink /proc/" << procpid << "/exe | sed \"s/\\(\\/" << appName << "\\)$//\""; string fRes; syscommand(command.str(),fRes); return fRes; } 

不要忘记修剪线后