How do I find the location of the executable in C?

2018-12-31 12:43发布

This question already has an answer here:

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

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

标签: c++ c linux unix path
9条回答
柔情千种
2楼-- · 2018-12-31 13:40

Remember that on Unix systems the binary may have been removed since it was started. It's perfectly legal and safe on Unix. Last I checked Windows will not allow you to remove a running binary.

/proc/self/exe will still be readable, but it will not be a working symlink really. It will be... odd.

查看更多
有味是清欢
3楼-- · 2018-12-31 13:45

I would

1) Use the basename() function: http://linux.die.net/man/3/basename
2) chdir() to that directory
3) Use getpwd() to get the current directory

That way you'll get the directory in a neat, full form, instead of ./ or ../bin/.

Maybe you'll want to save and restore the current directory, if that is important for your program.

查看更多
大哥的爱人
4楼-- · 2018-12-31 13:47

Use GetModuleFileName() function if you are using Windows.

查看更多
登录 后发表回答