James Kanze
10/23/2008 7:43:00 AM
On Oct 23, 12:28 am, Paavo Helde <nob...@ebi.ee> wrote:
> James Kanze <james.ka...@gmail.com> kirjutas:
> > There's definitely nothing in C++ which supports finding
> > where the executable was actually started. The closest you
> > can come is to try parsing argv[0] (which is supposed to
> > contain the name used to invoke the program---but in
> > practice doesn't always), then emulating the way the system
> > looks up executables---a lot of work, not completely
> > portable, and in practice, not necessarily reliable. On
> > specific platforms, you may have something in the system API
> > which would help (try GetModuleFileNameEx(
> > GetCurrentProcess(), NULL, ... ) under Windows---I don't
> > know of anything similar under Unix, however).
> In general, there is no way to relate an (unstarted
> executable, or any other) file to a certain directory.
Portably. For a number of systems (including Windows and most
Unix), there is a system specific way, but it's not portable;
even within the Unix community, different Unix may do it
differently.
> In Unix filesystems there are hardlinks and mounts, and on
> Windows there are subst commands, network drive mapping, etc,
> which mean that the same file can have multiple directory
> paths.
Which isn't necessarily a problem, as long as you can find one
of them.
> However, when launching the application, the kernel finds it
> in a certain directory path, and this information might be
> useful for the application. Windows makes it available through
> the GetModuleFileName[Ex]() function (as you said) and Linux
> makes it available through the /proc/PID/exe or
> /proc/self/exe, which is probably more reliable than argv[0].
But is pure Linux; there's no /proc/self under Solaris, for
example.
For some programs, it might be sufficient to search for argv[0]
in PATH environment variable; it's certainly not 100% reliable,
but it will cover a lot of use case scenarios. Of course, you
still have the portability issue that the path separator under
Unix is :, under Windows ;, and that the directory separator
must be / under Unix, but can be either \ or / under Windows
(and that an initial <alpha>: has a special meaning, and that
some files systems are case insensitive, others case sensitive).
If you control the installation, of course, the simplest
solution under Windows is to put such information in the
registry, during installation. Under Unix, a lot of programs
require you to set an environment variable, something like
MYPROG_HOME, which specifies the installation root.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34