C++ [Windows] Path to the folder where the executable is located [duplicate]
I need to access some files with fstream
in my C++ app on Windows. Those files are all located in subfolders of the folder where my exe file is located.
- What is the easiest and more important: safest way to get the path to the folder of the current executable?
Solution 1:
Use GetModuleFileName to find out where your exe is running from.
WCHAR path[MAX_PATH];
GetModuleFileNameW(NULL, path, MAX_PATH);
Then strip the exe name from path.
Solution 2:
GetThisPath.h
/// dest is expected to be MAX_PATH in length.
/// returns dest
/// TCHAR dest[MAX_PATH];
/// GetThisPath(dest, MAX_PATH);
TCHAR* GetThisPath(TCHAR* dest, size_t destSize);
GetThisPath.cpp
#include <Shlwapi.h>
#pragma comment(lib, "shlwapi.lib")
TCHAR* GetThisPath(TCHAR* dest, size_t destSize)
{
if (!dest) return NULL;
if (MAX_PATH > destSize) return NULL;
DWORD length = GetModuleFileName( NULL, dest, destSize );
PathRemoveFileSpec(dest);
return dest;
}
mainProgram.cpp
TCHAR dest[MAX_PATH];
GetThisPath(dest, MAX_PATH);
Update: PathRemoveFileSpec
is deprecated in Windows 8. However the replacement, PathCchRemoveFileSpec
, is available in Windows 8+ only. (Thanks to @askalee for the comment)
I think this code below might work, but I'm leaving the above code up there until the below code is vetted. I don't have a compiler set up to test this at the moment. If you have a chance to test this code, please post a comment saying if this below code worked and on what operating system you tested. Thanks!
GetThisPath.h
/// dest is expected to be MAX_PATH in length.
/// returns dest
/// TCHAR dest[MAX_PATH];
/// GetThisPath(dest, MAX_PATH);
TCHAR* GetThisPath(TCHAR* dest, size_t destSize);
GetThisPath.cpp
#include <Shlwapi.h>
#pragma comment(lib, "shlwapi.lib")
TCHAR* GetThisPath(TCHAR* dest, size_t destSize)
{
if (!dest) return NULL;
DWORD length = GetModuleFileName( NULL, dest, destSize );
#if (NTDDI_VERSION >= NTDDI_WIN8)
PathCchRemoveFileSpec(dest, destSize);
#else
if (MAX_PATH > destSize) return NULL;
PathRemoveFileSpec(dest);
#endif
return dest;
}
mainProgram.cpp
TCHAR dest[MAX_PATH];
GetThisPath(dest, MAX_PATH);
- NTDDI_WIN8 from this answer
- Thanks @Warpspace for the suggested change!