Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory of running program on Linux?

Tags:

c++

linux

unix

Hey, I've been writing a program (a sort of e-Book viewing type thing) and it loads text files from a folder within the folder of which the executable is located. This gives me a bit of a problem since if I run the program from another directory with the command "./folder/folder/program" for example, my program will not find the text, because the working directory isn't correct. I cannot have an absolute directory because I would like the program to be portable. Is there any way to get the precise directory that the executable is running from even if it has been run from a different directory. I've heard could combine argc[0] and getcwd() but argc is truncated when there is a space in the directory, (I think?) so I would like to avoid that if possible.

I'm on Linux using g++, Thanx in advance

like image 349
Ameer Jewdaki Avatar asked Dec 31 '22 02:12

Ameer Jewdaki


1 Answers

EDIT - don't use getcwd(), it's just where the user is not where the executable is.

See here for details.

On linux /proc/<pid>/exe or /proc/self/exe should be a symbolic link to your executable. Like others, I think the more important question is "why do you need this?" It's not really UNIX form to use the executable path to find ancillary files. Instead you use an environment variable or a default location, or follow one of the other conventions for finding the location of ancillary files (ie, ~/.<myapp>rc).

like image 144
plinth Avatar answered Jan 08 '23 02:01

plinth