argv [0]中的程序名

时间:2011-04-23 10:09:46

标签: objective-c

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

const char *proName=argv[0];

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

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

这里测试是我的程序的名称.... 它给了什么...完整的路径或程序名称? 感谢

2 个答案:

答案 0 :(得分:3)

正如您所注意到的,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);

答案 1 :(得分:2)

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

这取决于代码的调用方式。