Where Am I? GetModuleFileName Usage

Dear Dr. GUI (whatever it is!):

I want a program (written in Visual C++) to know in which directory it was started (not the working directory). This would allow me to read the .INI file without putting it in the WINDOWS directory or in the WIN.INI.

I’ve not been able to do this, but I have to admit that I am a newcomer to Windows programming. Digging in your CDs has not helped me; can you? Thank you.

Mauro Silverini

Dr. GUI replies:

“Whatever it is?” Well, I’m back, and I’m a doctor again. But it’s been a rough trip. I was praying so hard I thought I was going to change from Dr. GUI to Fr. GUI. But those priestly vows just aren’t my style.

In any case, have we got an API for you. Remembering that both .EXEs and .DLLs in Windows are called “modules” and that the name of the function you call when you need to ask Windows something almost always begins with “Get…”, a friend found the function GetModuleFileName. (Dr. GUI had yet to recover from the nice cactus, so he couldn’t quite see the screen.)

GetModuleFileName takes the module handle (NULL will work for an .EXE), a pointer to a buffer to receive the module name, and the size of the buffer. It returns the length of the string placed in the buffer. When it returns, the full file path, including directory information, will be in the buffer. You’ll have to parse the buffer to isolate the path name. (Hint: Start at the end and look for the first backslash using the C run-time library function strrchr.) I used the following code:

char acPath[256];
if ( GetModuleFileName( NULL,, acPath,, 256 ) != 0) {
   // guaranteed file name of at least one character after path \
   * ( strrchr( acPath, '\\' ) + 1 ) = '\0';
   AfxMessageBox( acPath );   // Use it 
}
else ; // error--GetModuleFileName failed