Home > Windows API > How to get current program directory?

How to get current program directory?

Use GetModuleFileName to get full path of executing program, and use PathRemoveFileSpec to remove file name part which leaves us with parent directory path of our program.

Here is a sample function which does this…

CString GetCurrentProgramParentDirectory()
{
   // Get current modules full path
   TCHAR szModuleFileName[MAX_PATH] = { 0 };
   GetModuleFileName( 0, szModuleFileName, MAX_PATH );

   // Remove file part for e.g. SomeExe.exe from C:/SomeProgram/SomeExe.exe
   // include shlwapi.h and link to shlwapi.lib
   PathRemoveFileSpec( szModuleFileName );

   // Return parent directory path
   return CString( szModuleFileName );
}// End GetCurrentProgramParentDirectory()
Advertisements
  1. June 12, 2008 at 12:36 am

    That’s true BM! 🙂

    Thanks posting additional information here. These days shlwapi is used in plenty AFAIK because of the utility functions it includes.

    I too use above code for retrieving parent folder in projects where shlwapi is not linked into and I wouldn’t link to shlwapi just for the sake of this one function.

    Well if it’s already there I would prefer to use this function. Also I wanted people to know there is something like this. 😉

  2. bw
    June 11, 2008 at 8:34 pm

    Come on, binding shlwapi.dll just to use 1 function that can be replaced by inline strrchr (or _tcsrchr for TCHARs) is in my opinion not a good way to optimize your code…

    *(strrchr(szModulePath, ‘\\’) + 1) = ”;

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: