Firstly, I would like to say that I don't mean the full path, what
GetModuleFileName or argv[0] yield. Is there a smarter solution than dismissing everything before the last backslash?

- 2,559
- 7
- 38
- 65
-
What platform are you on? I suppose Windows? – Luka Ramishvili May 13 '12 at 14:36
-
2What's is wrong with taking everything after the last path delimiter? Myself, I just use my own written basename function on argv[0]. – Anon Mail May 13 '12 at 14:39
-
There are also path functions to do it. – chris May 13 '12 at 14:39
-
2Luka, you supposed correctly, tags weren't added accidentally ;) – 0x6B6F77616C74 May 13 '12 at 14:41
3 Answers
First of all you want to get hold of the full path to the executable by calling GetModuleFileName
passing NULL
as the module handle. Then call PathFindFileName
to pull out the file name component.
There is in fact a difference between GetModuleFileName
and argv[0]
. The latter is the name used to start the process. It could be missing the full path, but more importantly here, it could be missing the .exe
extension. If you want to know the actual filename then you need to use GetModuleFileName
.

- 601,492
- 42
- 1,072
- 1,490
-
1That's what I was trying to find. I find it *really* funny how that example uses `void main` though. Seriously, Microsoft? – chris May 13 '12 at 14:49
-
1Microsoft is allowed to do it like that because they write the compiler. As such they can make use compiler specific extension that you and I (as good standards following citizens) can't. – Martin York May 13 '12 at 15:40
If you use .NET, then here's an answer. But internally it may be calling GetModuleFileName
.

- 1
- 1

- 889
- 1
- 11
- 20
In Windows C/C++ there is a global variable extern char * _pgmptr
that can be read as well as an unsafe string copy from _get_pgmptr(char ** buffer)
.
Caveats
Only call _get_pgmptr() if your program has a narrow entry point, like main() or WinMain(). The _pgmptr global variable contains the full path to the executable associated with the process. For more information, see _pgmptr, _wpgmptr.
If a DLL is loaded in two processes, its file name in one process may differ in case from its file name in the other process.
The global variable _pgmptr is automatically initialized to the full path of the executable file, and can be used to retrieve the full path name of an executable file.