28

Possible Duplicate:
How to get the application executable name in Windows (C++ Win32 or C++/CLI)?

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

Community
  • 1
  • 1
John MacIntyre
  • 12,910
  • 13
  • 67
  • 106

5 Answers5

56

You can do this via the GetModuleFileName function.

TCHAR szFileName[MAX_PATH];

GetModuleFileName(NULL, szFileName, MAX_PATH)
GuidedHacking
  • 3,628
  • 1
  • 9
  • 59
Garett
  • 16,632
  • 5
  • 55
  • 63
3

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
  • 53,498
  • 9
  • 91
  • 140
3

See GetModuleFileName()

Thanatos
  • 42,585
  • 14
  • 91
  • 146
2

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
  • 798
  • 1
  • 6
  • 17
  • 5
    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 Oct 22 '10 at 21:07
  • 1
    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 Oct 22 '10 at 21:10
  • 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 Oct 22 '10 at 21:16
  • 1
    Thanks for the distinction of it only working on console apps. – John MacIntyre Oct 25 '10 at 15:14
  • no, tested under visual studio 2017 AND MFC app. I wrote: TCHAR szFileName[MAX_PATH + 1]; GetModuleFileName(NULL, szFileName, MAX_PATH + 1); auto instanceID = CString(szFileName); it WORKS. – ingconti Sep 21 '18 at 14:22
-1

For console apps:

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

Prints full path.

egrunin
  • 24,650
  • 8
  • 50
  • 93