GetModuleFileNameA

Retrieves the fully qualified path for the executable file of the calling process.

Syntax

DWORD GetModuleFileNameA(
  _In_opt_ HMODULE hModule,
  _Out_writes_to_(nSize, return + 1) LPSTR lpBaseName,
  _In_ DWORD nSize
);
C++

Parameters

Parameter Type Description
hModule _In_opt_ HMODULE A handle to the loaded module whose path is to be retrieved. If this parameter is NULL, the function returns the path of the executable file of the calling process.
lpBaseName _Out_writes_to_(nSize, return + 1) LPSTR A pointer to a buffer that receives the null-terminated string that specifies the module's path.
nSize _In_ DWORD The size of the buffer pointed to by lpBaseName, in characters.

Return Value

Type Description
DWORD If the function succeeds, the return value is the length of the string copied to the buffer, in characters, not including the terminating null character.

If the function fails, the return value is 0. To get extended error information, call GetLastError.

If the buffer pointed to by lpBaseName is not large enough, the return value is the size of the buffer required to hold the path, in characters, including the terminating null character. The first nSize characters in the buffer will contain the path, and the last character will be a null terminator.

Remarks

The path returned is the path to the module's source file. This is typically the path of the .exe file for the main executable module.

To retrieve the path for a module other than the current process's executable file, use the hModule parameter to specify a handle to the module.

If the path exceeds the size of the buffer, the function will write as many characters as possible into the buffer, followed by a null terminator. The return value will be the size of the buffer specified by nSize.

If the module handle is NULL, the function returns the path of the executable file of the calling process.

Requirements

Header: Declared in WinBase.h

Library: Use Kernel32.lib

DLL: Kernel32.dll

Example

#include <windows.h>
#include <iostream>
#include <vector>

int main() {
    TCHAR szPath[MAX_PATH];

    if (GetModuleFileName(NULL, szPath, MAX_PATH) > 0) {
        std::cout << "Module Path: " << szPath << std::endl;
    } else {
        DWORD error = GetLastError();
        std::cerr << "Failed to get module file name. Error code: " << error << std::endl;
    }

    return 0;
}
C++

See Also

GetModuleFileName (Unicode version)
GetCurrentProcess
GetLastError