Reputation:
I'm wondering how I can get the directory of my program on Linux. For instance, if I have my program located under /home/myproject/
and I get the directory, it should be /home/myproject/
regardless of what directory I'm calling the program from. I need this functionality because I need to be able to access a configuration file located under the same folder as my program, regardless of where the program's folder is located.
I've tried using getcwd()
, but here's what it does:
If I'm currently in the same folder as the program is, it will work. However, if I was in /root
and tried executing the program which is located under /home/myproject
, it would give me /root
.
If I just do something like...
std::ifstream is("anotherfile");
It will work as long as I'm in the same directory, but it does the same as above when I'm not.
Upvotes: 0
Views: 501
Reputation: 1
On Linux, you could use /proc/
. Read carefully proc(5).
I'm suggesting reading the symlink in /proc/self/exe
using readlink(2). It gives your executable. You might use dirname(3) on it to get its directory. Be also aware of realpath(3) which might be useful (actually not, since, as commented by Daniel Schepler, /proc/self/exe
is a canonical path....).
This is Linux specific, and won't work in rare pathological cases (your executable being removed or renamed during execution). See this.
Remember that Linux don't have folders (they are just a GUI artefact) but directories. See also opendir(3), readdir(3), closedir(3), stat(2), nftw(3), etc....
At last, the Unix tradition is to keep user-specific configuration files under $HOME
(often with hidden dotfile, e.g. $HOME/.inputrc
) and system-wide configuration files under /etc/
. You can get $HOME
with getenv(3) as getenv("HOME")
. See environ(7). In pathological cases such a getenv
could fail.
BTW, you could even adopt a convention of testing with getenv
if some particular environment variable is set (e.g. MYPROGCONFIG
) and if it is set, use that as your configuration file. Don't forget to document such conventions.
Upvotes: 3