【问题标题】:How to get program path [duplicate]如何获取程序路径[重复]
【发布时间】:2010-12-23 09:30:01
【问题描述】:

可能重复:
how to find the location of the executable in C

我正在使用 GTK+ 用 C++ 编写一个多平台应用程序,但我遇到了问题。我必须得到程序路径。例如,当程序在/home/user/program(或C:\Users\user\program.exe)中时,我有/home/user/(或C:\Users\user\)。

我可以以及如何做到这一点?

【问题讨论】:

  • 您需要绝对还是相对路径?

标签: c++ gtk


【解决方案1】:

对于 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]处有,但是:

注意:命令行中可执行文件的名称 操作系统提供给一个进程不一定相同 在调用进程提供给 创建过程函数。操作系统可能会预先设置一个完全 提供的可执行文件名的限定路径 合格的路径。

【讨论】:

  • 大声笑,我在 1 年前问过这个问题......我现在不需要这个答案,抱歉 :)
  • 好的,但也许其他人会觉得它有用;)
【解决方案2】:

argv[0] 包含程序名称和路径。我在这里遗漏了什么吗?

【讨论】:

  • 可能不会,除非您对argv[0] 的内容有疑问。
  • 你不应该相信argv[0] - 请参阅link
【解决方案3】:

在窗户上..

#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;

你应该看看这个问题..

How do I get the directory that a program is running from?

【讨论】:

  • 没有通用的解决方案吗? :)
  • 为什么要投反对票?该解决方案是一个非常有趣的替代 IMO,特别是如果主要不在您手中,例如如果您正在编写库。 +1
  • 这个答案不正确;您正在提供当前工作目录,这与应用程序路径完全不同... 在您链接的线程中,存在同样的混乱
  • @OliverZendel,这个答案是正确的。在 Windows 中,这是错误的,而您的答案是正确的。在linux上它是完全正确的。 readlink of /proc/pid/exe 的作用与 Windows 中的 GetModuleFileName 相同。无论哪种方式,接受的答案都是完全错误的。
  • @Shahabaz,感谢您的澄清!
猜你喜欢
  • 2013-07-06
  • 1970-01-01
  • 1970-01-01
  • 2012-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-02
  • 2013-02-24
相关资源
最近更新 更多