How to get the program path

Possible duplicate:
how to find executable file location in C

I am writing a multi-platform C ++ application using GTK + and I have a problem. I have to get the software path. For example, when the program is located in /home/user/program (or C:\Users\user\program.exe ), I have /home/user/ (or C:\Users\user\ ).

Maybe and how can I do this?

+4
source share
3 answers

argv[0] contains the name of the program with the path. Did I miss something?

+3
source

For Win32 / MFC C ++ programs:

 char myPath[_MAX_PATH+1]; GetModuleFileName(NULL,myPath,_MAX_PATH); 

Also follow the comments at http://msdn.microsoft.com/en-us/library/windows/desktop/ms683156%28v=vs.85%29.aspx ,

Essentially: WinMain does not include the program name in lpCmdLine, main (), wmain () and _tmain () should have it in argv [0], but:

Note. The name of the executable file on the command line, the operating system provides a process that is not necessarily identical to that on the command line that the calling process gives CreateProcess. The operating system may have a qualified path to an executable name that is provided without a qualified path.

+5
source

In the windows ..

 #include <stdio.h> /* defines FILENAME_MAX */ #ifdef WINDOWS #include <direct.h> #define GetCurrentDir _getcwd #else #include <unistd.h> #define GetCurrentDir getcwd #endif char cCurrentPath[FILENAME_MAX]; if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath))) { return errno; } cCurrentPath[sizeof(cCurrentPath) - 1] = '/0'; /* not really required */ printf ("The current working directory is %s", cCurrentPath); 

Linux

 char szTmp[32]; sprintf(szTmp, "/proc/%d/exe", getpid()); int bytes = MIN(readlink(szTmp, pBuf, len), len - 1); if(bytes >= 0) pBuf[bytes] = '\0'; return bytes; 

And you should look at this question ..

How to get the directory from which the program is running?

+2
source

Source: https://habr.com/ru/post/1333167/


All Articles