On Jun 26, 2:13 pm, emarcari <emarc...@gmail.com> wrote:
> On Jun 21, 12:11 pm, Thomas Børlum <bor...@gmail.com> wrote:
> > I'm writing a c++ program that needs to read a file. I'm
> > trying to read a file that is in the same directory as the
> > executable.
> > Everything works fine if I execute the program while in the
> > program's directory. What I need to do is read that file
> > regardless of where (cwd) I execute the program from,
> > without hardcoding the absolute since the program might be
> > moved or be in differant locations on other computers.
> > What should I do?
> > PS. I'm using the boost filesystem framework if it helps.
> You may use getenv, doing something like this:
> std::string source_dir = getenv( "srcdir" );
Don't ever write something like this. It will generally crash,
since getenv returns a null pointer if the specified variable
isn't set (and "srcdir" generally isn't).
With regards to obtaining the full pathname of the executable,
something like this depends on whoever starts the executable
setting the appropriate variable. Bash sets "_" to the full
path name, but I don't know of any other program which sets
anything, so unless you can guarantee that your program will
only be started by bash, you can't use this.
> Look at
> http://www.cplusplus.com/reference/c...ib/getenv.html,
> that there are another examples.
Which very clearly says that getenv may return a null pointer,
so it cannot be used as an initializer for a string.
--
James Kanze (GABI Software) email:
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