0

I am trying to run an application, app. I do this by running ./app in the directory of app. This application has a dependency, graphics/file.bmp. Everything works when I run ./app in that directory.

If I instead run from the parent folder, it can't find graphics/file.bmp when I run ./app_directory/app

What is the cleanest way to resolve this? I would like to cd into the directory of the file no matter where I am running the program from. I am on OSX and would be thrilled by a solution that works across all unix machines.

Chet
  • 1,209
  • 1
  • 11
  • 29
  • You could use `argv[0]` to find out what directory your application actually sits in, and then append that to the path - or, if it doesn't matter where you are when you run the code, use `chdir`. – Mats Petersson Oct 01 '14 at 20:46
  • @cdhowie - This is a nice solution for me. You should post it as an answer. – Chet Oct 01 '14 at 20:56

2 Answers2

0

You could try writing a bash script that you could run from any directory and it will cd into the directory that successfully runs the program, but this won't actually change the working directory at which your terminal is sitting. In case you don't know how to do that: make a file called build (or whatever you want) and place it in the parent folder. In that file put the following code:

cd app_directory
./app

After you create the script run chmod u+x <script-name>, which will make it an executable. Once this is done you can just run ./<script-name> and it should run your program just fine.

nromito
  • 31
  • 1
  • 1
0

You can do this on the first line of main():

chdir(dirname(argv[0]));

dirname() removes the last path component from the input ("a/b/c" turns into "a/b") and if there is only one path component then it returns ".". Passing this return value directly into chdir() will change the working directory to the directory containing the binary.

cdhowie
  • 158,093
  • 24
  • 286
  • 300