0

If I have an executable: project/bin/exec, which caches data into a file.txt in its active directory, the location where file.txt will be saved depends on how I run the program:

  • project/file.txt if I run it from project with bin/exec
  • project/bin/file.txt if I run it from project/bin with ./exec

I'd like the program to always use the directory of the executable and I'd like to find out if there's a non-programatic way of forcing it to do it.

I'm interested in UNIX/Windows, does this even make sense?

Programatically, I know I could get the executable's directory by using boost or std::experimental filesystem, perhaps args[0] argument and use that path for I/O.

Is that the way to do it?

LogicStuff
  • 19,397
  • 6
  • 54
  • 74

1 Answers1

3

One way of doing this on Unix (part of the question) would be to use a script which would chdir before running executable.

Something like this:

#!/bin/ksh

loc=`dirname $0`
cd $loc
echo $PWD
SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • 1
    That will not work on Windows. – perencia Dec 24 '15 at 19:08
  • @perencia, yeah, missed OP is interested in Windows solution as well. I am pretty sure similar techinque could be employed in Windows, however, I am not familiar with Microsoft products that well. – SergeyA Dec 24 '15 at 19:11
  • It's not completely clear in the question but I assume that a cross-platform is what is asked for. I posted as a comment a link to a related cross-platform question. – perencia Dec 24 '15 at 19:11
  • @perencia, I doubt you can do it both cross-platform and non-programmatically :) – SergeyA Dec 24 '15 at 19:13
  • that part of the question i do not understand. Isn't what you have done "programmatically" ? So, is non-programatically the same as "outside the main program" ? For non-programmatic i've always thought as "by-configuration", but leveraging the actual configuration :) – perencia Dec 24 '15 at 19:15
  • @SergeyA Thanks for the answer, meanwhile, I've decided. I'll do it programatically :) Cross-platform and less painful. – LogicStuff Dec 24 '15 at 19:18