to get exe name in Program

Apr 26, 2010 at 6:56pm
Hi,
is it possible to write program in c or C++ that we can exe name of that program into the file
Apr 27, 2010 at 5:25pm
Hey there...

This might not be what you're looking for...

1
2
3
4
5
6
#include <iostream.h>

int main(int argc, char* argv[])
{
    cout<<argv[0];   //This will give you the exe name
}



Hope that helped ;-)
Apr 27, 2010 at 5:42pm
On Windows, use the GetModuleFileName() function:
http://www.google.com/search?btnI=1&q=msdn+GetModuleFileName

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <windows.h>

using namespace std;

int main()
  {
  char filename[ MAX_PATH ];
  DWORD size = GetModuleFileNameA( NULL, filename, MAX_PATH );
  if (size)
    cout << "EXE file name is: " << filename << "\n";
  else
    cout << "Could not fine EXE file name.\n";
  return 0;
  }

There is no reliable way to do this on *nix. (There are very good technical reasons as to why... Also, on *nix, you shouln't care where your executable is.)

Using argv[0] is a common solution, but also unreliable. There is no standard as to what may be stored in it, other than something to the effect that it should be how the process was started. On both Windows and Unix systems, it is entirely possible that the value could point to something other than your actual executable's name. (In practice, however, this is rare.) Also, it may very well not have the full path to your executable. For example, run attaboy's code by typing different ways to start the executable:
D:\prog\foo> a.exe
a.exe

D:\prog\foo> a
a

D:\prog\foo> d:\prog\foo\a
d:\prog\foo\a

D:\prog\foo> _

Hope this helps.
Apr 28, 2010 at 3:56pm
thx for a reply
Topic archived. No new replies allowed.