tags:

views:

152

answers:

2

Say I have a command line C program which is currently executing, and I want to read a file or execute another binary in the same directory - how can I find out what directory that is?

Note that I'm not looking for the current working directory. The user may have invoked my original program in any of the following ways (and possibly others I don't know about).

  • ../../program
  • /home/matt/program
  • PATH=$PATH:/home/matt program

Ideally I'm looking for something which will work on a unix system and windows via MinGW.

+1  A: 

Concat getcwd() and dirname(argv[0])

dimba
That would work in the first and second case, but not in the third unless I'm mistaken.
Matt Sheppard
Yep, this doesn't work in the 3rd case. Actually argv[0] can be set to anything by executing program, therefore it's not to relay on it. A good answer is in link supplied by @mark4o in comment to your question.
dimba
+2  A: 

http://c-faq.com/osdep/exepath.html

According to the C FAQ it can't be done reliably

http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe

Timothy Pratley
Mandating that the CWD contains helper executables is for sure not acceptable to the users I know -- including me.
AProgrammer
Not sure what you are getting at AProgrammer... I'm not suggesting anything about helper executables. If the program needs to start with cwd being where the program resides then its perfectly valid to check for the basename of argv[0] existing in cwd. There are much better suggestions from http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe as mark40 pointed out. The point is - it is impossible to find the executing programs location reliably, so it should either be removed as a requirement or he can make best effort to detect.
Timothy Pratley
Edited to link to other thread which has system specific work arounds
Timothy Pratley