Link to home
Start Free TrialLog in
Avatar of Cyber-Dragon
Cyber-Dragon

asked on

C++ Get Current Directory Without Exe

I'm trying to find the current of my executable without the file name and .exe at the end.

I've been using GetCurrentPath() to find the entire path with the .exe but I only need the current path without the .exe
Avatar of jkr
jkr
Flag of Germany image

Try the following:
#include <windows.h>
#include <shlwapi.h>
 
#pragma comment(lib,"shlwapi32.lib")
 
BOOL GetModulePath(TCHAR* pBuf, DWORD dwBufSize) {
 
  if (GetModuleFileName(NULL,pBuf,dwBufSize)) {
 
    PathRemoveFileSpec(pBuf); // remove executable name
 
    return TRUE;
  }
 
  return FALSE;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If you are looking for the directory that contains your .exe, you can get the exe path as you have done, then you can use _splitpath to break the path into it's components, and _makepath to put the path to the folder back together:

http://msdn.microsoft.com/en-us/library/e737s6tf(VS.80).aspx
http://msdn.microsoft.com/en-us/library/sh8yw82b(VS.80).aspx
Avatar of Cyber-Dragon
Cyber-Dragon

ASKER

No, sorry those didn't work. I know that there is a function that didn't require a maximum size limit because I used it in this project before but I deleted it and I don't remember what the name of it is.
There isn't a maximum size limit, you just need to specify a buffer size when calling *any* Windows APIs, since they need to know how much space you can provide. You can pretty much provide any space you like, e.g.
TCHAR pBuf = new TCHAR[1024 * 1024 * 1024];
 
GetModulePath(pBuf,1024 * 1024 * 1024);
 
delete [] pBuf;

Open in new window

BTW, if you just don't like size limits, that's OK, then use a std::string for that, e.g.
#include <string>
typedef std::basic_string<TCHAR> tstring;
 
#include <windows.h>
#include <shlwapi.h>
 
#pragma comment(lib,"shlwapi32.lib")
 
tstring GetModulePath() {
 
  TCHAR acPath[MAX_PATH];
 
  if (GetModuleFileName(NULL,acPath,dwBufSize)) {
 
    PathRemoveFileSpec(acPath); // remove executable name
 
    return tstring(acPath);
  }
 
  return tstring(_T("<none>"));
}

Open in new window

Thanks guys I found the solution. Looks like jkr was right about using GetCurrentDirectory(). Just had to be configured correctly.
CString GetAppPath()
{
      TCHAR szEXEPath[MAX_PATH];
    GetModuleFileName ( NULL, szEXEPath, MAX_PATH );
      for(int i=strlen(szEXEPath)-2; i>-1; i--)
      {
            if(szEXEPath[i]=='\\'){
                  szEXEPath[i+1] = '\0';
                  break;
            }
      }
      return CString(szEXEPath);
}