正如你所注意到的,argv[0]
可以(但不總是)包含可執行文件的完整路徑。如果你只想要的文件名,一個解決辦法是:
#include <libgen.h>
const char *proName = basename(argv[0]);
正如墊指出,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);
一些相關的信息:http://stackoverflow.com/questions/273691/using-progname-instead-of-argv0 – Mat 2011-04-23 10:19:47