【发布时间】:2010-12-23 09:30:01
【问题描述】:
我正在使用 GTK+ 用 C++ 编写一个多平台应用程序,但我遇到了问题。我必须得到程序路径。例如,当程序在/home/user/program(或C:\Users\user\program.exe)中时,我有/home/user/(或C:\Users\user\)。
我可以以及如何做到这一点?
【问题讨论】:
-
您需要绝对还是相对路径?
我正在使用 GTK+ 用 C++ 编写一个多平台应用程序,但我遇到了问题。我必须得到程序路径。例如,当程序在/home/user/program(或C:\Users\user\program.exe)中时,我有/home/user/(或C:\Users\user\)。
我可以以及如何做到这一点?
【问题讨论】:
对于 Win32/MFC c++ 程序:
char myPath[_MAX_PATH+1];
GetModuleFileName(NULL,myPath,_MAX_PATH);
还请注意以下注释 http://msdn.microsoft.com/en-us/library/windows/desktop/ms683156%28v=vs.85%29.aspx,
本质上:WinMain不包括lpCmdLine中的程序名,main()、wmain()和_tmain()应该在argv[0]处有,但是:
注意:命令行中可执行文件的名称 操作系统提供给一个进程不一定相同 在调用进程提供给 创建过程函数。操作系统可能会预先设置一个完全 提供的可执行文件名的限定路径 合格的路径。
【讨论】:
argv[0] 包含程序名称和路径。我在这里遗漏了什么吗?
【讨论】:
argv[0] 的内容有疑问。
argv[0] - 请参阅link
在窗户上..
#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;
你应该看看这个问题..
【讨论】:
readlink of /proc/pid/exe 的作用与 Windows 中的 GetModuleFileName 相同。无论哪种方式,接受的答案都是完全错误的。