getopt函數的功能

頭文件: #include

定義函數
int getopt(int argc,char * const argv[ ],const char * optstring);

函數說明 
getopt()用來分析命令行參數。參數argc和argv是由main()傳遞的參數個 數和內容。參數optstring 則代表欲處理的選項字符串。此函數會返回在argv 中下一個的選項字母,此字母會對應參數optstring 中的字母。如果選項字符串裏的字母后接着冒號“:”,則表示還有相關的參數,全域變量optarg 即會指向此額外參數。如果getopt()找不到符合的參數則會印出錯信息,並將全域變量optopt設爲“?”字符,如果不希望getopt()印出錯 信息,則只要將全域變量opterr設爲0即可。

返回值 如果找到符合的參數則返回此參數字母,如果參數不包含在參數optstring 的選項字母則返回“?”字符,分析結束則返回-1。
範例 #include<stdio.h>
#include<unistd.h>
int main(int argc,char **argv)
{
int ch;
opterr = 0;
while((ch = getopt(argc,argv,”a:bcde”))!= -1)
switch(ch)
{
case ‘a’:
printf(“option a:’%s’/n”,optarg);
break;
case ‘b’:
printf(“option b :b/n”);
break;
default:
printf(“other option :%c/n”,ch);
}
printf(“optopt +%c/n”,optopt);
}
執行  
$./aaa –b
option b:b
$./aaa –c
other option:c
$./aaa –a
other option :?
$./aaa –a12345
option a:’12345'

==========================淫蕩的分割線=====================================

另一篇

#include <unistd.h>
#include <getopt.h>

extern char *optarg; //指向optstring中有':'的參數在使用時,其後面緊接著的設定值字串。
extern int optind; //表示argv[]中第一個不屬於getopt的參數索引。
extern int opterr; //1: 表示若誤用未列在optstring中的字元當參數,且optstring的第一個字元不是':'時,
        向stderr顯示錯誤訊息。預設為1,若設為0:表不顯示錯誤訊息。
extern int optopt; //指示哪個參數字元的處理出錯,若是用到沒有列在optstring中的字元,
        則以'?'字元表示(若optstring的第一個字元是':',則以':'字元取代'?'字元)。

getopt( int argc, char **argv,
   "ab:c:deq");  <--稱為optstring,後面加':'表示該字元參數在使用時,後面需給設定值。

[功能]:處理"-h"形式的單一字元參數。

[Return Value]
 某字元值:表成功找到該字元 參數。
 ':':表示需要設定值的參數,沒給設定值。
 '?':表示字元不在optstring中。
 '-1':表示需要被找字元已經沒了。

還有
getopt_long()和get_opt_long)only(),處理"--help"形式的長字串參數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章