Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to find where the executable is located? 1

Status
Not open for further replies.

niputaidea

Programmer
Jun 22, 2006
1
US
I need to find out where the executable that is currently running is located. For example, if a have an executable foo.exe located in c:\bar\foo.exe and I execute foo.exe from c:\a\very\long\path, I still need to know that foo.exe is located in c:\bar. I can get the directory where it was called from but not where it is located. Any help will be gladly appreciated.

Thx

NPI
 
The name of the executable will be in the first parameter of main. eg
Code:
int main (int argc, const char* argv[])
The name of the executable will be in argv[0]. If this doesn't give you the full path name then do something like
Code:
FILE* pipe;
char  dir[256];
pipe = popen ("pwd", "r");
fgets (pipe, dir, sizeof (dir));
fclose (pipe);
I'm writing this off the top of my head so they may be a few syntax errors.
 
xwb said:
pipe = popen ("pwd", "r");
Unfortunately, "pwd" won't work on Windows.

Use the getcwd() function instead. On UNIX it's in <unistd.h> and on Windows it's in <direct.h>
 
Unfortunately, the pwd/cwd is not the location of the executable.

Under Linux, you can find the executable by reading the file [tt]/proc/$PID/exe[/tt].
 
Platform-dependent alternatives:

1. MS Visual C++ RTL only:
use _pgmptr global variable
Code:
extern char* _pgmptr;

2. MS Windows API only:
use
Code:
DWORD GetModuleFileName(
  HMODULE hModule,    // handle to module to find filename for
  LPTSTR lpFilename,  // pointer to buffer to receive module path
  DWORD nSize         // size of buffer, in characters
);
Set hModule == 0 for the current process. Use _MAX_PATH predefine constant from <stdlib.h>.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top