4 Comments

  1. [md]
    “`
    //A c function to get your own executable’s execution directory.
    // Sometimes you want to know the program source

    #ifndef MAX_PATH
    #define MAX_PATH 256
    #endif

    static char * get_path_to_me(void);
    static char *
    get_path_to_me ()
    {
    static char buffer[MAX_PATH];
    char *cp;
    int len;
    if ((len = readlink (“/proc/self/exe”, buffer, sizeof (buffer) – 1)) != -1)
    {
    buffer[len] = ‘\0′;
    cp=strrchr(buffer,’/’);
    *cp=’\0′;
    fprintf (stderr, “\n%s version 0.9, date Compiled: %s, “, cp+1, __DATE__);
    fprintf (stderr, “is executed from %s\n”, buffer); //program executes, dirname ok
    *cp=’/’;
    }
    else
    *buffer = ‘\0’;
    return (buffer);
    }
    #if 0 // set to 1 to test as stand-alone, leave as 0 if you want to include this function in your code.
    /**
    * @brief main
    * @param argc
    * @param argv
    * @return
    */
    int
    main (int argc, char *argv[])
    {
    char *pgm;
    char *pgmx;
    pgm = strdup (get_path_to_me ());
    strcpy(buffer,pgm);
    printf(“\nfull path = %s, directory=%s program=%s\n”,buffer,dirname(pgm),basename(pgm));
    return 0;
    }
    #endif

    1. Thanks for sharing the C code.

      This is a nice trick:

      readlink (“/proc/self/exe”, buffer, sizeof (buffer) – 1)

  2. This is awesome.

    I still don’t completely understand it,
    but I definitely understand it better than before
    and I have a lot to learn about bash fundamentals anyway.

    Thanks for the write-up!

Leave a Reply

Your email address will not be published. Required fields are marked *