How can I get the path where the binary that is executing resides in a C program?
I'm looking for something similar to __FILE__
in ruby/perl/PHP (but of course, the __FILE__
macro in C is determined at compile time).
dirname(argv[0])
will give me what I want in all cases unless the binary is in the user's $PATH
... then I do not get the information I want at all, but rather ""
or "."
Path aliases replace well-known directories with keywords, using a format similar to that of environment variables in Windows. In this way, binary paths of well-known locations become language neutral and independent of the drive where the binary is located.
Totally non-portable Linux solution:
#include <stdio.h>
#include <unistd.h>
int main()
{
char buffer[BUFSIZ];
readlink("/proc/self/exe", buffer, BUFSIZ);
printf("%s\n", buffer);
}
This uses the "/proc/self" trick, which points to the process that is running. That way it saves faffing about looking up the PID. Error handling left as an exercise to the wary.
The non-portable Windows solution:
WCHAR path[MAX_PATH];
GetModuleFileName(NULL, path, ARRAYSIZE(path));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With