tags:

views:

142

answers:

4

I can find what directory the process is running in using GetCurrentDirectory(), but what about finding the directory the EXE resides in?

+5  A: 

GetModuleFileName or GetModuleFileNameEx.

Jerry Coffin
Can you give an example? It's not clear to me where I get the HMODULE handle.
John
@John: `GetModuleHandle(NULL)`
Billy ONeal
If you want the main executable file, `GetModuleHandle(NULL)`. If you want a DLL, the handle to that DLL is (among other things) passed when `DllMain` is called.
Jerry Coffin
OK, cool. So this gets me a pull path including the file-name. Is there a handy function to get me the full directory path, without the file-name? e.g takes c:\temp\app.exe and returns c:\temp?
John
@John: Yes, it's PathRemoveFileSpec -> http://msdn.microsoft.com/en-us/library/bb773748(v=VS.85).aspx
Billy ONeal
John
A: 

I'd go for GetCommandLine

Neil Moss
That won't work if the program is started from the command line; the full path is not always specified there.
Billy ONeal
@Billy ONeal - duly noted. Thanks.
Neil Moss
A: 

In visual C++, we use

CString m_sAppFolder =  __targv[0] ;

which returns a string like "C:\blah\blah\executable_name.exe"

PSUnderwood
-1 for: 1. Unneeded dependence on MFC. 2. Having the same problem as Neil Moss's answer. 3. Using nonstandard `__targv`.
Billy ONeal
A: 

Please forgive my ignorance, but concerning Jerry Coffin's answer, should we pass GetModuleHandle(NULL) as a first parameter to GetModuleFileName()? Wouldn't it be sufficient to simply pass NULL? i.e. calling the function the following way:

GetModuleFileName(NULL, ..., ...)?

I was under the impression that those two function calls are equivalent:

GetModuleFileName(NULL, lpFileName, nSize)

and

GetModuleFileName(GetModuleHandle(NULL), lpFileName, nSize)

Isn't this true?

Thanks in advance.

vbdasc