How do I get the absolute path to the directory of the currently executing command in C? I'm looking for something similar to the command dirname "$(readlink -f "$0")" in a shell script. For instance, if the C binary is /home/august/foo/bar and it's executed as foo/bar I want to get the result /home/august/foo.
3 Answers
Maybe try POSIX realpath() with argv[0]; something like the following (works on my machine):
#include <limits.h> /* PATH_MAX */
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
char buf[PATH_MAX];
char *res = realpath(argv[0], buf);
(void)argc; /* make compiler happy */
if (res) {
printf("Binary is at %s.\n", buf);
} else {
perror("realpath");
exit(EXIT_FAILURE);
}
return 0;
}
3 Comments
August Karlstrom
Thanks for the solution, although your example prints the path for the binary rather than its directory. Using the function
dirname in libgen.h solves it.August Karlstrom
According to the documentation at gnu.org/software/libc/manual/html_node/Limits-for-Files.html the constant
PATH_MAX accounts for the string terminator, so +1 is not strictly needed.August Karlstrom
Unlike
readlink -fthe call to realpath doesn't work if the binary is executed through the PATH variable.One alternative to argv[0] and realpath(3) on Linux is to use /proc/self/exe, which is a symbolic link pointing to the executable. You can use readlink(2) to get the pathname from it. See proc(5) for more information.
argv[0] is allowed to be NULL by the way (though this usually wouldn't happen in practice). It is also not guaranteed to contain the path used to run the command, though it will when starting programs from the shell.
argv[0]is not enough in this case since I need the absolute path.