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.

Matt Sheppard
  • 116,545
  • 46
  • 111
  • 131
  • 3
    See http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe – mark4o Sep 09 '09 at 05:51

2 Answers2

2

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

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

Finding current executable's path without /proc/self/exe

Community
  • 1
  • 1
Timothy Pratley
  • 10,586
  • 3
  • 34
  • 63
  • Mandating that the CWD contains helper executables is for sure not acceptable to the users I know -- including me. – AProgrammer Sep 09 '09 at 07:05
  • 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 Sep 09 '09 at 08:59
  • Edited to link to other thread which has system specific work arounds – Timothy Pratley Sep 09 '09 at 09:05
1

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

dimba
  • 26,717
  • 34
  • 141
  • 196
  • That would work in the first and second case, but not in the third unless I'm mistaken. – Matt Sheppard Sep 09 '09 at 05:51
  • 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 Sep 09 '09 at 06:01