How to get program path [duplicate]

2019-02-18 12:03发布

问题:

Possible Duplicate:
how to find the location of the executable in C

I'm writting an multi-platform app in C++ using GTK+ and I have a problem. I must get program path. E.g., when program is in /home/user/program (or C:\Users\user\program.exe), i have /home/user/ (or C:\Users\user\).

Can and how I can do this?

回答1:

argv[0] contains the program name with path. Am I missing something here?



回答2:

For Win32/MFC c++ programs:

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

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

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

Note: The name of the executable in the command line that the operating system provides to a process is not necessarily identical to that in the command line that the calling process gives to the CreateProcess function. The operating system may prepend a fully qualified path to an executable name that is provided without a fully qualified path.



回答3:

On 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 do I get the directory that a program is running from?



标签: c++ gtk