ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
I have an execuatable that could be moved around in my file sys tree. I need to find out - in my C++ exe code - which dir the exe is.
I know I could use dirname/which in shell and env var passed into c code. I think they work most of the time when symbolic link is not invoved. I prefer a function in c that could tell me where the execuatble is located.
Well, argv[0] contains the path that was used to run the program and getcwd() will get you the path of the current working directory which will be where the program was executed from. By munging the two together you should be able to come up with something. If the first character of argv[0] is "/", then that is the path name of the program. If it is not, then append argv[0] to the path returned from getcwd() and voila, FM. There could be some "../../" in this but it will still be a vaild path.
If the executeable was found with the PATH environment variable, the above won't find it and you will have to spin all of the paths in PATH and check each one to see if the file is there.
Out of curiosity, does the program do something based on its location in the tree?
To answer Malicious's question, my program does rely on where the executable is for the following info:
where the shared lib is;
where the some resource files located;
Also, I do need to think about the sym link and PATH cases.
Good to know that!
I probably go with the script method because I only know my pid after my shared lib is resolved, also for portability(other unix) reason I will not use /proc.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.