Long story made short, I felt the need for my program to be able to identify it's executable location. I stumbled across this function: GetModuleFileName ( NULL, szEXEPath, 2048 ); and from what I read was under the impression that this returned the full path of the executable. I did not experience this. Can someone please tell me what I am doing wrong?
This is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <tchar.h>
#include <iostream>
#include <Windows.h>
usingnamespace std;
int _tmain(int argc, _TCHAR* argv[])
{
/* I thought this should display the path to the executable, but I am wrong */
TCHAR szEXEPath[2048];
cout << GetModuleFileName ( NULL, szEXEPath, 2048 );
/* PAUSE PROGRAM */
int i;
cin >> i;
return 0;
}
This is my output:
103
From some of what I read, it said this returned the length of the path (is that useful??) and other places I read that this actually returns the path. Given that I got a number, it is likely it is returning the length. What can I do to get this right?
Ok, so I found that if I looked to see what was in szEXEPath, each array index had an ASCII number in it... so I figured maybe it was returning the ASCII value instead. I re-wrote the code like so and it does what I think it should...
Yes, Duoas has it correct, but to put it more simply:
GetModuleFileName() takes 3 arguments:
1.) A handle to a module (Just use NULL to retrieve the "current" prog's path)
2.) A pointer to a char[] buffer
3.) The size of the buffer
And it returns the number of characters that were copied to the buffer.
So to use it you would write something like this:
1 2 3
char buffer[MAX_PATH];//always use MAX_PATH for filepaths
GetModuleFileName(NULL,buffer,sizeof(buffer));
cout << "Filepath:" << buffer << "\n";
And it will print the filepath of the current exe.
SigmaSecurity (4)
if the IDE is VS2005
your code have one error
error C2664: 'GetModuleFileNameW' : cannot convert parameter 2 from 'char [260]' to 'LPWCH'