问题描述:

How can I get the application directory in C++ on Linux/Unix. getcwd() returns the directory 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

相关阅读:
Top