0

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.

1
  • @hyde argv[0] is not enough in this case since I need the absolute path. Commented Feb 26, 2015 at 15:27

3 Answers 3

4

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
Unlike readlink -fthe call to realpath doesn't work if the binary is executed through the PATH variable.
1

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.

Comments

1

I have come to the conclusion that there is no portable way for a commpiled executable to get the path to its directory. The obvious alternative is to pass an environment variable to the executable telling it where it is located.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.