Find the application's directory in Windows

Hi, I am using GetModuleFileName(NULL, application_path, length) in order to get the application directory but it returns the entire path, including the name of the executable. What I want is only the directory where the current executable is located. Is there any other way, I am doing something wrong? Thanks!
Last edited on
closed account (1vRz3TCk)
1
2
3
4
5
6
7
8
9
10
11
// With STL string
#include <string>

char        szAppPath[MAX_PATH] = "";
std::string strAppDirectory;

::GetModuleFileName(0, szAppPath, sizeof(szAppPath) - 1);

// Extract directory
strAppDirectory = szAppPath;
strAppDirectory = strAppDirectory.substr(0, strAppDirectory.rfind("\\"));
Thanks! That worked (with some adaptations)
::GetModuleFileName(0, szAppPath, sizeof(szAppPath));
::std::cout << "the full path is :" << szAppPath;

// use strrchr to set the executable ''
char * pc =strrchr(szAppPath,"\\");
if (pc) {
*pc = '\0';
}
::std::cout << "the needed path is :" << szAppPath;


the result is :

the full path is : *:*\*\*\*.exe

the needed path is : *:*\*\*

hope this is helpful for you.
Why don't you use PathRemoveFileSpec() ? It is exported from shlwapi.dll
Great example, kamillia. One small thing, though, I believe you need to use single quote in the char* pc, i.e.,

char * pc=strrchr(szAppPath,'\\');

I get an operator overload error if I use double quotes, but I tried the example only in my WinApp.
Even better, modoran. That's one I didn't know about. I've found myself more and more frequently using functions from shlwapi.h/.dll. I guess I ought to actually open up the .h file and take a look at what all is in it.
Last edited on
Don't need to open any windows header files, it is all documented in MSDN (I have an offline copy that came with Visual Studio 2010 though)
To :Lamblion (609)

yeah, that's right! it should be single quote.
Topic archived. No new replies allowed.