0

Possible Duplicates:
Win32: Find what directory the running process EXE is stored in
How to get the application executable name in Windows (C++ Win32 or C++/CLI)?

hi, i want to make my application run on statup,it uses some of files in the same directory.it works good but when it start at startup the GetCurrentDirectory is "c:\Documents and Settings\User\"..but i want the actual path of the exe file.how i can get it in c++. please help me. thanks.

Community
  • 1
  • 1
YAHOOOOO
  • 939
  • 4
  • 19
  • 27
  • Can you rephrase yourself? What exactly is your problem? And what exactly you want? `GetCurrectDirectory()` is supposed to give you the current directory which I think you want! – Nawaz Jan 15 '11 at 11:32
  • I think u couldn't understand my que. well...GetCurrectDirectory() gives correct current directory but when the program starts on startup the value of GetCurrectDirectory() is "c:\Documents and Settings\User\" for me.I want to know another way to find the executed executalbe's directory path. – YAHOOOOO Jan 15 '11 at 11:38
  • thanks İsmail 'cartman' Dönmez, – YAHOOOOO Jan 15 '11 at 11:41

2 Answers2

4

Try using GetModuleFileName or GetModuleFileNameEx.

Do this:

wchar_t exeDirectory[1024]; //to store the directory
DWORD ret = GetModuleFileName(NULL, exeDirectory, 1024);
if ( ret )
{
  /*the path to your EXE is stored in the variable "exeDirectory" - use it */
}

Note I'm passing NULL as first argument, because MSDN says,

"If this parameter is NULL, GetModuleFileName retrieves the path of the executable file of the current process."

which is what you want. Right?

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • thanks,its working...but if i am doing GetModuleFileName(NULL, exeDirectory, 1024) it is working well.so,what useness of hModule=GetModuleHandle(NULL). – YAHOOOOO Jan 15 '11 at 11:50
  • That's good. In fact the MSDN says *"If this parameter is NULL, GetModuleFileName retrieves the path of the executable file of the current process."*... that means, I don't need to use GetModuleHandle(). Let me remove it from the code! – Nawaz Jan 15 '11 at 11:57
-1

Using argv maybe:

int main(int argc, char* argv[])
{
  // argv[0] is the path to binary file you're running
  // ...
  return 0;
}

The profit is that this method is platform-independent and has no needs for any system calls.

shybovycha
  • 11,556
  • 6
  • 52
  • 82
  • not exactly, it gives the command as issued to the command line, or more specifically, the exec() call, or its Windows equivalent. This is not (necessarily) an absolute path to the executable. You should be able to get the absolute path by combining current working directory and argv[0] though if it is not an absolute directory. But then getting the current working directory may not be implemented platform independently and more troublesome checking if argv[0] is an absolute path is also platform dependent. – wich Jan 15 '11 at 12:00