getting the path to the executing program
glynn.clements at virgin.net
Sat Jan 10 05:21:31 EST 2004
oleg at pobox.com wrote:
> > is there a function, related to getProgName, which returns the (absolute)
> > path to the current program?
> > basically, i want to be able to read a file which i know will be in the
> > same directory as the current program, but not necessarily in the same
> > directory that we're running it from.
> Actually, if you want to read a file located in the same directory
> as the executable itself, you don't need the absolute path of the
> executable. You merely need any path to the executable that is valid with
> respect to the working directory at the start-up time.
> Some four years ago I wrote a similar code that seems to work reliably
> across HP/UX, Solaris, Linux, FreeBSD and various versions of Winxx
> (from Windows98 onwards). The application has been deployed in more
> than thousand copies and nobody has complained regarding the path.
> The application reliably finds the name of a file from the
> application's own directory no matter how the application was invoked:
> from its own directory by name, from its own directory as "./appname",
> from its own directory by the absolute or relative (../dir/appname)
> name, or from some other directory by the absolute or relative name,
> or by a symbolic link.
You omitted the most important case: from an arbitrary directory via a
simple filename, looked up via $PATH.
For that case, you need to iterate through the components of $PATH
until you find one which contains a suitably-named file which has
execute permission for the current user.
That still doesn't handle the pathological cases, e.g. where the
filesystem has been changed such that the original command would no
longer refer to the same executable, or where argv doesn't contain
the filename used, but it's likely to be close enough for the cases
where someone isn't deliberately trying to make it fail.
Glynn Clements <glynn.clements at virgin.net>
More information about the Haskell