Home > Backend Development > C++ > How Can I Get the Full Path of My Executable in C/C ?

How Can I Get the Full Path of My Executable in C/C ?

Susan Sarandon
Release: 2024-12-14 19:21:12
Original
420 people have browsed it

How Can I Get the Full Path of My Executable in C/C  ?

Locating the Executable's Full Path in C

In C and C , determining the full path of the currently executing program can be challenging. This is because argv[0], which contains the program name, often does not provide the complete path.

Unix-based Systems

To reliably retrieve the executable's location on Unix systems with "/proc":

  • Use readlink("/proc/self/exe", buf, bufsize) (Linux)
  • Use readlink("/proc/curproc/file", buf, bufsize) (FreeBSD)
  • Use readlink("/proc/self/path/a.out", buf, bufsize) (Solaris)

On Unix systems without "/proc":

  • If argv[0] starts with "/", it is the absolute path.
  • If argv[0] contains "/", append it to the current working directory.
  • Search for argv[0] as an executable in the directories specified in $PATH.

Windows

On Windows systems, use the following code:

GetModuleFileName(NULL, buf, bufsize);
Copy after login

Additional Considerations

  • Check if the executable is a symlink and resolve it accordingly (not necessary if using the "/proc" method on Linux).
  • Note that it is the responsibility of the calling process to set argv[0] correctly, especially in untrusted situations (e.g., setuid executables).

The above is the detailed content of How Can I Get the Full Path of My Executable in C/C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template