How to Determine the Executable Location in C
In C/C , obtaining the complete path of the currently executing program can be challenging. Specifically, using argv[0] may not provide the full path.
Unix Systems without /proc
If your Unix system lacks the /proc file system, consider the following strategies:
- Check if argv[0] begins with a slash (/): This indicates an absolute path.
- If argv[0] contains slashes (/): Append it to the current working directory (cwd).
- Otherwise, search for the executable argv[0] in directories specified in the $PATH environment variable.
Unix Systems with /proc
For Unix systems with /proc, you can use one of the following methods:
- Linux: readlink("/proc/self/exe", buf, bufsize)
- FreeBSD: readlink("/proc/curproc/file", buf, bufsize)
- Solaris: readlink("/proc/self/path/a.out", buf, bufsize)
Windows Systems
On Windows, use the GetModuleFileName function:
GetModuleFileName(NULL, buf, bufsize);
Additional Considerations
- Verify that the executable is not a symlink and resolve it if necessary.
- The calling process should set argv[0] correctly for this information to be accurate.
The above is the detailed content of How Can I Get the Full Path of My C/C Executable?. For more information, please follow other related articles on the PHP Chinese website!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn