【问题标题】:Program name in argv[0]argv[0] 中的程序名称
【发布时间】:2011-04-23 10:09:45
【问题描述】:

我读到argv[0] 包含程序名称,即我们保存项目的名称.... 但是当我在我的目标 C 命令行程序中执行以下语句时

const char *proName=argv[0];

我在控制台中看到以下内容:

/Users/apple/Library/Developer/Xcode/DerivedData/testaehcfzilirskhjbifrwresgppvbp/Build/Products/Debug/test

这里的 test 是我的程序的名称.... 那么它给出了什么...完整路径或程序名称? 谢谢

【问题讨论】:

标签: objective-c


【解决方案1】:

如您所见,argv[0] 可以(但不总是)包含可执行文件的完整路径。如果您只想要文件名,一种解决方案是:

#include <libgen.h>

const char *proName = basename(argv[0]);

正如 Mat 所指出的,argv[0] 并不总是可靠的——尽管它通常应该可靠。这取决于你到底想要完成什么。

也就是说,在 Mac OS X 上还有另一种获取可执行文件名称的方法:

#include <mach-o/dyld.h>
#include <libgen.h>

uint32_t bufsize = 0;

// Ask _NSGetExecutablePath() to return the buffer size
// needed to hold the string containing the executable path
_NSGetExecutablePath(NULL, &bufsize);

// Allocate the string buffer and ask _NSGetExecutablePath()
// to fill it with the executable path
char exepath[bufsize];
_NSGetExecutablePath(exepath, &bufsize);

const char *proName = basename(exepath);

【讨论】:

  • execl("/your/executable", "this will appear in in argv[0]", "arg1", ...); 会打败它。记住这一点。
【解决方案2】:

您不能依赖包含特定内容的 argv[0]。有时你会得到完整的路径,有时只有程序名称,有时完全是别的东西。

这取决于代码是如何被调用的。

【讨论】:

    猜你喜欢
    • 2011-05-01
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 2010-09-07
    • 2014-09-22
    • 2011-01-02
    相关资源
    最近更新 更多