where my executable is

Michael Veksler VEKSLER@il.ibm.com
Mon Sep 24 02:32:00 GMT 2001


> Is there a function that would give the absolute path to the directory
> where my executable was executed from?

If your main looks like: int main(int argc, char *argv[])
Then you normally can use argv[0] (no guarantee).

Here is pseudocode (I do something similar in ksh):

// Finds the full path version of "dir"
char* resolve_dir(char *dir)
{
   if (dir starts with '/'):
      return dir
   else:
     return getcwd()+'/'+dir
}

if (argv[0] contains '/'):
   return resolve_dir(the directory part of argv[0]);


// Search through $PATH;
name=argv[0]; // note that name contains no '/'
foreach element in $PATH:
   if exists executable file element+'/'+name:
      return resolve_dir(element+'/'+name);

// Nothing found
error "can't find the directory, the caller did not pass relevant info"





More information about the Gcc-help mailing list