• 20Aug

    One day I needed to make an embedded Python interpreter in a Fortran/C program aware of its path, since it should search for a predefined python source code file in the same directory from the binary is located.

    Now, this introduces some issues, as the Fortran/C program can be runned in many ways:

    1. Absolute path (/home/asbjorn/test1/main)
    2. Standing in the directory and run ./main
    3. Having the /home/asbjorn/test1/ in your $PATH variable (Linux/UNIX), and type ‘main’.

    Now, the simplest approach is to use the “int argc, char *argv[]” variables inside your ‘int main()’ method. Then the “argv[0]” would contain the binary file name, including any absolute path if that what being used. But, if your application is in your $PATH variable, it wont work.

    A ‘dirty’ trick could be to use:

    char path[255];
    path = system("which main");

    but, its not recommended using this approach. Another very hackish and cool solution is the following:

    #include <stdlib.h>
    #include <stdio.h>
    #include <sys/param.h>
    int main(int argc, char* argv[])
    {
       char path[MAXPATHLEN];
       int length;
       length = readlink("/proc/self/exe", path, sizeof(path));
       if(length<0) {
          fprintf(stderr,"error resolving /proc/self/exe!\n");
          exit(1);
       }
       path[length] = '\0';
       printf("The absolute path to this running binary is: %s\n", path);
     
       return 0;
    }

    Another approach which is often used is to include some kind of configuration file that contains this path. Or, in my case, I could specify another folder which should hold my Python files. This approach would probably make more sense in the long run, as it is more flexible.

    So, in case you find yourself in this situation, then feel free to copy-paste the code and save the day ;) Have a good summer people!