Following code:
#include <iostream> #include <Windows.h> using namespace std; int main () { LPWSTR buffer; //or wchar_t * buffer; GetModuleFileName(NULL, buffer, MAX_PATH) ; cout<<buffer; cin.get(); cin.get(); }
Should show the full path where the program executes. But in VS 2012 I get the error:
uninitialized local variable 'buffer' used
What's wrong in code?
You need to give it a buffer that can hold some characters;
wchar_t buffer[MAX_PATH];
for example.
VS properly points out that you are using an uninitialized buffer - buffer var is a pointer to WSTR, but it was not initialized with the static buffer, neither it was allocated. Also you should remember that MAX_PATH is often not enough, especially on modern systems with long pathnames.
Since you are using C++, it would be a good practice to use it's features. I can suppose the following code:
vector<wchar_t> pathBuf; DWORD copied = 0; do { pathBuf.resize(pathBuf.size()+MAX_PATH); copied = GetModuleFileName(0, &pathBuf.at(0), pathBuf.size()); } while( copied >= pathBuf.size() ); pathBuf.resize(copied); wstring path(pathBuf.begin(),pathBuf.end()); cout << path;
Don't use wstring as buffer directly: it is not defined to have a continuous buffer in every implementation (but usually is)
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