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.
-
Do you mean the directory where the executable is placed? – sashoalm Jul 19 '13 at 14:55
-
Yes I do. The executable path is fine too. – azmeuk Jul 19 '13 at 14:56
-
1Which Operating system? – RedX Jul 19 '13 at 14:56
-
3I feel like this might be OS-dependent, as I don't think the C standard mandates anything about programs having to run from a file – Drew McGowen Jul 19 '13 at 14:57
-
Only a duplicate if he's talking about Windows – Drew McGowen Jul 19 '13 at 14:59
-
For unix: http://stackoverflow.com/questions/606041/how-do-i-get-the-path-of-a-process-in-unix-linux Either way, it's a dupe. – Michael Kohne Jul 19 '13 at 15:00
-
The most general way would be the better, but OS specific answers are good too. I need it for Linux, Mac and Windows – azmeuk Jul 19 '13 at 15:02
4 Answers
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.

- 38,596
- 7
- 91
- 135
-
2I 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
In Linux use readlink /proc/self/exe
In Windows use GetModuleFileName()
with say hModule = NULL

- 3,647
- 1
- 24
- 44
-
+1 showing actual solutions is way better than saying "it's impossible" (which it clearly isn't). – Jul 19 '13 at 15:01
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.

- 75,001
- 122
- 434
- 781
-
Nope, it shows the executable as it was executed (i.e., if you did `./a.out -foo bar`, then `argv[0]` is `./a.out` – Drew McGowen Jul 19 '13 at 14:59
You can look at argv[0], but I'm not sure if it's guaranteed to give you a path.

- 1,225
- 11
- 21
-
@nouney On windows 7 x86 it stores full name of executable. Try it yourself. I have MSVC2005. – kvv Jul 19 '13 at 15:02
-