1

Do you know how to get the absolute location of the current program in C ? I am not talking about the current directory, but the directory where the executable file is placed.

sashoalm
  • 69,127
  • 105
  • 396
  • 720
azmeuk
  • 3,346
  • 3
  • 29
  • 56

4 Answers4

4

C standard doesn't provide a way of doing it; it has to be done using OS-specific APIs. You might as well have a tiny embedded os programmed directly on a chip; what would the program location be, then?

And on normal OSes I think it could be a security vulnerability.

Bartek Banachewicz
  • 37,611
  • 7
  • 90
  • 133
  • 2
    I don't think the C standard says "you can't get the full path of the executable". I'd suggest re-phrasing this as "this is only possible using OS-dependent APIs". As to "what would the program location be, then": embedded systems often use `int main(void)` exclusively. –  Jul 19 '13 at 15:00
  • @H2CO3 Thanks, corrected. – Bartek Banachewicz Jul 19 '13 at 15:02
2

In Linux use readlink /proc/self/exe

In Windows use GetModuleFileName() with say hModule = NULL

blganesh101
  • 3,559
  • 23
  • 42
  • +1 showing actual solutions is way better than saying "it's impossible" (which it clearly isn't). –  Jul 19 '13 at 15:01
0

The C standard does not define a way to do that as far as I know. The only way would be to use OS-dependent functions, which means you do it in Linux/Windows/Mac, not "in C".

One way is to get the executable's filename which is usually placed in argv[0]. But I'm not sure if it is always safe to assume it to be the full path of the executable.

In BusyBox, for example, they use that trick to make a single executable appear as many separate programs, using symlinks. The executable checks what argv[0] is, and behaves accordingly.

sashoalm
  • 69,127
  • 105
  • 396
  • 720
0

You can look at argv[0], but I'm not sure if it's guaranteed to give you a path.

jsp
  • 1,155
  • 10
  • 21