The easiest way would be to either put your program in a pre-known place (/bin, /usr/bin, etc.). If not, you can use the argv[0], remove the program name (the last part), and use that as your working directory to prefix all relative paths (if you want relative paths to be relative to where your program is).
Also, you can determine the path of your program using the method above (use argv[0]
), and then call a chdir()
with this directory. All relative paths from then on would be relative to where the program is. Note, however, that in this case, you have to determine if argv[0]
holds an absolute path. If not, you have to get the current working dir (getcwd()
) and then append the directory part of argv[0]
. Note, however, that changing the current work dir. is not a good idea, usually, as if a user gives you a file path as an argument, it will be relative to your current work dir, not relative to where the program is stored.
Some examples: Imagine your program lives in /usr/bin
. You can call your program as:
/usr/bin/myprog
(that would be argv[0]
. Prune the executable name and you have your dir.) Or, being, say, in /usr
:
./bin/myprog
Now, argv[0]
is a relative path. You have to prepend current working dir (/usr
) to the one in the argv[0]
: /usr/./bin/myprog
, and then again prune the executable name. The directory would be again /usr/bin
.