tags:

views:

61

answers:

5

How can I get the current instance's file name & path from within my native win32 C++ application?

For example; if my application was c:\projects\testapps\getapppath.exe it would be able to tell the path is c:\projects\testapps\getapppath.exe

+6  A: 

You can do this via the GetModuleFileName function.

TCHAR szFileName[MAX_PATH];

GetModuleFileName( NULL, szFileName, MAX_PATH )
Garett
That's it. I knew it was something simple.
John MacIntyre
+1  A: 

GetCurrentProcess, then QueryFullProcessImageName

Other answers are better for your own process - this is preferred for remote ones. Per the docs:

To retrieve the module name of the current process, use the GetModuleFileName function with a NULL module handle. This is more efficient than calling the GetProcessImageFileName function with a handle to the current process.

To retrieve the name of the main executable module for a remote process in win32 path format, use the QueryFullProcessImageName function.

Steve Townsend
+2  A: 

See GetModuleFileName()

Thanatos
+2  A: 

UPDATE: Works only for console applications!

The program's path is passed as first argument, It's stored in argv[0] in the main(argc, argv[]) function.

Ed.C
No it doesn't. Windows passes the unmodified parameter string passed as the 2nd parameter to CreateProcess. It can contain anything at all. IF only 1 string is passed to CreateProcess, then it will look for the path to the exe in argv[0] - but the path doesn't have to be canonical in any way - just satisfy the SearchPath function. Its certainly a convention, but theres no guarantee that argv[0] contains anything remotely usable.
Chris Becke
That's what I was thinking, but my winmain's signature is int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
John MacIntyre
Except that if one of the three posix calls execl, execle or execlp was used to start the program, you are at the mercy of the program that made the exec call for the value in argv[0].
David Harris
Thanks for the distinction of it only working on console apps.
John MacIntyre
A: 

Tested:

int _tmain(int argc, _TCHAR *argv[])
{
    _tprintf(L"%s", argv[0]);
    return 0;
}

Prints full path.

egrunin