2011-04-23 38 views
1

,我讀了argv[0]保持程序的名稱即由我們保存工程.... 但這個名字的時候我在客觀C命令行程序執行以下語句程序名稱[0]

const char *proName=argv[0]; 

我在控制檯看到以下內容:

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

這裏測試我的程序的名稱.... 那麼,是什麼給它...完整路徑或程序名? 謝謝

+0

一些相關的信息:http://stackoverflow.com/questions/273691/using-progname-instead-of-argv0 – Mat 2011-04-23 10:19:47

回答

2

你不能依賴於含有特定的東西argv[0]。有時你會得到完整的路徑,有時只是程序名稱,有時候完全是其他的東西。

這取決於如何調用代碼。

3

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

execl(「/ your/executable」,「這將出現在argv [0]」 ,「arg1」,...);'會擊敗那個。記在心上。 – Mat 2011-04-23 10:17:28

+0

@Mat這是真的。 – 2011-04-23 10:19:45