开发者

C++ Get Application Directory *NIX

开发者 https://www.devze.com 2023-02-11 22:12 出处:网络
How can I get the application directory in C++ on Linux/Unix. getcwd() returns the direc开发者_如何学运维tory from which the application was run, but I want the actual directory which the build is sit

How can I get the application directory in C++ on Linux/Unix. getcwd() returns the direc开发者_如何学运维tory from which the application was run, but I want the actual directory which the build is sitting in.

I know you can get this from the main() but I dont really have access to it, and I've been told you cant rely on it (Is that true?).


You can see this answer:

c++ - Finding current executable's path without /proc/self/exe - Stack Overflow


In general in a unix system you cannot assume that there is even a file or directory that is still pointing to the executable file. For example the file/directory could have been deleted while the program was running (this is impossible in windows but not a problem in unix/linux). On the other side there may be multiple names that are pointing to the same physical file (hard links) none of which is the principal one... what is "the name" of the file in this case?

There is no safe portable way to get the name of the program because there can be many names or no names at all that are pointing to the program. If you must find the name of the program it means you're trying to do something wrong and there's probably a better solution.

EDIT:

While there is no general portable approach for all *x systems, under linux you can use the name /proc/self/exe to open the executable file. This will work even if the file is not pointed any more by any directory (e.g. even if the file has been "deleted" while was running). The actual file (inode) of a running process will always be available if the process is still running, what may be missing is the name of the file (i.e. a directory listing that is pointing to that inode).


argv[0] will give you the full path to the executable - don't know if this is a general standard

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号