Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly use GetModuleFileName?

Tags:

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?

like image 485
Sunrise Avatar asked Sep 13 '13 09:09

Sunrise


2 Answers

You need to give it a buffer that can hold some characters;

 wchar_t buffer[MAX_PATH];  

for example.

like image 122
Mats Petersson Avatar answered Oct 23 '22 13:10

Mats Petersson


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)

like image 25
kingsb Avatar answered Oct 23 '22 13:10

kingsb