Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can program get executable name of itself? [duplicate]

Tags:

c++

windows

Possible Duplicate:
Extracting the current executable name

I created a program that reads configuration from ini file, the name of that file should be identical to name of executable but of course with its extension. So If I name it myprogram.exe the config should be myprogram.ini, and if I change name of the exe after compilation it should look accorting to its new name.

I know that it is possible to get program name from argv[0] but this works only if it starts from command line, when it is clicked in explorer this array is empty.

As I read through the answers here I think it has to do something with this function: https://stackoverflow.com/a/10572632/393087 - But I can't find any good example of usage of that function, I'm very beginner to c++ and general function definitions (like that presented on microsoft pages) are too hard for me to understand, but when I get a working example it is a snap for me to comprehend.

like image 727
rsk82 Avatar asked May 30 '12 11:05

rsk82


2 Answers

#include <windows.h>
#include <Shlwapi.h>
// remember to link against shlwapi.lib
// in VC++ this can be done with
#pragma comment(lib, "Shlwapi.lib")

// ...

TCHAR buffer[MAX_PATH]={0};
TCHAR * out;
DWORD bufSize=sizeof(buffer)/sizeof(*buffer);
// Get the fully-qualified path of the executable
if(GetModuleFileName(NULL, buffer, bufSize)==bufSize)
{
    // the buffer is too small, handle the error somehow
}
// now buffer = "c:\whatever\yourexecutable.exe"

// Go to the beginning of the file name
out = PathFindFileName(buffer);
// now out = "yourexecutable.exe"

// Set the dot before the extension to 0 (terminate the string there)
*(PathFindExtension(out)) = 0;
// now out = "yourexecutable"

Now in out you have a pointer to the "base name" of your executable; keep in mind that it points inside buffer, so when buffer goes out of scope out is not valid anymore.

like image 186
Matteo Italia Avatar answered Nov 04 '22 13:11

Matteo Italia


GetModuleFileName(NULL, .....)

But I can't find any good example of usage of that function

You haven't tried hard enough. "Examples" section in "GetModuleFileName" article on msdn

like image 26
SigTerm Avatar answered Nov 04 '22 12:11

SigTerm