I have a program which opens a file by using a relative path (for instance '..').
Now the problem is, when I execute the program from another directory, the relative path is not relative to the program but relative to the working directory. Thus, if I start the program with '/path/to/program/myprog' it fails to find the file.
Is there a way to execute the program independently of the working directory? Id est, as If the working directory were the directory where the program is located? Or am I just thinking in a too complicated way and there is a much easier way to refer to a file, which location is only known by its path relative to the path of the program file?
解决方案
If program is not doing it by itself, it is a bad program. Bad programs should be wrapped with a bit of Bash scripting:
#!/bin/bash
set -e
cd $(readlink -f $(dirname $0))
exec ./myprog $*
The script above determines the directory where it is located, then changes current working directory to that directory and runs a program myprog from there, passing all parameters transparently. Thus, you have to put this script into the same directory where your program is located and run it instead of your program.
Assuming that you have the access to the source code and can fix the program, then use proc fs to determine the program's location and then use absolute path.
For example, /proc/self/exe will always be a symlink pointing at the binary file of the current process. Use readlink to read its value, then cut executable name and you got the directory.