如何找到在C可执行文件的位置 [英] how to find the location of the executable in C

查看:139
本文介绍了如何找到在C可执行文件的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有在C / C ++查找当前执行的程序的位置(完整路径)?一个办法

Is there a way in C/C++ to find the location (full path) of the current executed program?

(有问题的argv [0] 是,它并没有给出完整的路径。)

(The problem with argv[0] is that it does not give the full path.)

推荐答案

要总结一下:


  • 在Unix系统与的/ proc 真直度和realiable的方法是:

  • On Unixes with /proc really straight and realiable way is to:


  • 的readlink(的/ proc /自/ EXE,BUF,BUFSIZE)(Linux)的

的readlink(的/ proc / curproc /文件,BUF,BUFSIZE)(FreeBSD的)

readlink("/proc/curproc/file", buf, bufsize) (FreeBSD)

的readlink(的/ proc /自/路径/ a.out的,BUF,BUFSIZE)(的Solaris)

readlink("/proc/self/path/a.out", buf, bufsize) (Solaris)

在Unix系统没有的/ proc (即,如果上面的失败):

On Unixes without /proc (i.e. if above fails):


  • 如果argv的[0]以/(绝对路径)开始,这是路径。

  • If argv[0] starts with "/" (absolute path) this is the path.

否则,如果包含的argv [0]/(相对路径)追加到CWD
(假设它尚未更改)。

Otherwise if argv[0] contains "/" (relative path) append it to cwd (assuming it hasn't been changed yet).

否则搜索目录在 $ PATH 可执行的argv [0]

Otherwise search directories in $PATH for executable argv[0].

此后,它可能是合理的,检查可执行文件是否实际上不是一个符号链接。
如果它是解决它相对于符号链接的目录。

Afterwards it may be reasonable to check whether the executable isn't actually a symlink. If it is resolve it relative to the symlink directory.

这一步是不是(至少对于Linux)的/ proc方法必要的。
还有在proc符号链接直接指向可执行文件。

This step is not necessary in /proc method (at least for Linux). There the proc symlink points directly to executable.

请注意,它是由调用进程[0] 正确设置 argv的。
这是最正确不过也有场合,当调用进程不能被信任的时代(例如setuid的可执行文件)。

Note that it is up to the calling process to set argv[0] correctly. It is right most of the times however there are occasions when the calling process cannot be trusted (ex. setuid executable).

在Windows上:使用 GetModuleFileName(NULL,BUF,BUFSIZE)

On Windows: use GetModuleFileName(NULL, buf, bufsize)

这篇关于如何找到在C可执行文件的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆