Tuesday, March 18, 2008

[C++] How to retrieve Application Path

Hi There,
welcome back to "the Best Resource on the web for Application Path retrieval" (Jack Jones - Collective Development); after .NET Application Path and JAVA Application Path we present a quick reference about how to retrieve Application Path using C++ and raw WinAPIs.

There are two common ways to retrieve App Path in C++ in a windows environment:

1) GetCurrentDirectory - this is probably the most common way to do it but it has a Drawback: the current directory path is not always the directory from where your assembly is being executed; You can alway change your current directory with a call to SetCurrentDirectory Indeed. This function fills a buffer with the current directory path (without filename), and returns the path size (termination character excluded); in case of errors it returns 0, In case the buffer is too short it returns the buffer required size:

#define PATH_LENGTH 1023

char buffer[PATH_LENGTH];
CString AppPathNoFileName;
int rv = GetCurrentDirectory(PATH_LENGTH,buffer);

if((!rv) || (rv > PATH_LENGTH))
//something wrong!
AppPathNoFileName = buffer;

Ref: GetCurrentDirectory

2) GetModuleFileName - this is safer if you wanna be sure to get the directory from which the current assembly is being executed. With this method you get not only the path but the file name as well, so you might wanna parse the resulting string in order to cut the filename if you don't need it. If the buffer is too short the path gets trucated. The function returns the size of path (number of characters- excluding end of string character) or 0 if an error occurs:

HINSTANCE hInst = AfxGetInstanceHandle();
char _buffer[PATH_LENGTH];
CString AppPath, AppPathNoName;

if(!GetModuleFileName(hInst, _buffer, PATH_LENGTH))
AppPath = _buffer;
AppPathNoName = AppPath.Left(ApplicationPath_.Find("\\[appname].[appext]", 0));

Ref: GetModuleFileName

That's all; Stay out of troubles.

No comments: