C++ 如何获取程序路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4517425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get program path
提问by m4tx
Possible Duplicate:
how to find the location of the executable in C
可能的重复:
如何在 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\
).
我正在使用 GTK+ 在 C++ 中编写一个多平台应用程序,但我遇到了问题。我必须得到程序路径。例如,当程序在/home/user/program
(或C:\Users\user\program.exe
)时,我有/home/user/
(或C:\Users\user\
)。
Can and how I can do this?
可以和我如何做到这一点?
采纳答案by Jaywalker
argv[0]
contains the program name with path. Am I missing something here?
argv[0]
包含带有路径的程序名称。我在这里错过了什么吗?
回答by Oliver Zendel
For Win32/MFC c++ programs:
对于 Win32/MFC C++ 程序:
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,
另请注意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:
本质上:WinMain 在 lpCmdLine 中不包含程序名称,main()、wmain() 和 _tmain() 应该在 argv[0] 处包含它,但是:
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.
注意:操作系统提供给进程的命令行中的可执行文件的名称不一定与调用进程提供给 CreateProcess 函数的命令行中的名称相同。操作系统可能会在没有完全限定路径的情况下为可执行名称添加完全限定路径。
回答by Soner G?nül
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
Linux
char szTmp[32];
sprintf(szTmp, "/proc/%d/exe", getpid());
int bytes = MIN(readlink(szTmp, pBuf, len), len - 1);
if(bytes >= 0)
pBuf[bytes] = '##代码##';
return bytes;
And you should look at this question..
你应该看看这个问题..