I'm trying to get the path of my currently running executable like so:
#include <Windows.h>
#include <stdio.h>
int main()
{
LPWSTR current_filepath = (LPWSTR)malloc(MAX_PATH * sizeof(LPWSTR));
DWORD path_size = 0;
DWORD buffer_size = GetModuleFileNameW(0, current_filepath, path_size);
if (!buffer_size)
{
DWORD err = GetLastError();
perror("Error: ");
}
else
{
wprintf(L"%ls \n", current_filepath);
}
}
But when I run the application with a breakpoint on the if I can see that the buffer_size is 0 and the current_filepath is not filled with the path it should be.
I'm not sure on what I did wrong so if anyone has a pointer in the right direction it would be greatly appreciated.
1 Answer
I'm trying to get the path of my currently running executable like so:
Getting the file path to the currently running EXE basically involves passing NULL or nullptr to GetModuleFileName.
Here's what you really want:
LPCWSTR GetPathToRunningExe()
{
wchar_t szPath[MAX_PATH] = { 0 };
DWORD dwSize = GetModuleFileNameW(NULL, szPath, ARRAYSIZE(szPath));
wchar_t* result = NULL;
if (dwSize > 0)
{
size_t count = wcslen(szPath) + 1;
result = (wchar_t*)malloc(count * sizeof(szPath[0]));
wcscpy_s(result, count, szPath);
}
return result;
}