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.
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.