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.
Right-click the “Start” menu shortcut for the application, and select More > Open file location. This will open a File Explorer window that points to the actual application shortcut file. Right click on that shortcut, and select “Properties.” No matter how you located the shortcut, a properties window will appear.
They indicate that the path should be passed to the system with minimal modification, which means that you cannot use forward slashes to represent path separators, or a period to represent the current directory, or double dots to represent the parent directory.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With