getopt(分析命令列參數)
#include<unistd.h>
int getopt(int argc,char * const argv[ ],const char * optstring);
extern char *optarg;
extern int optind, opterr, optopt;
函數說明 getopt()用來分析命令列參數。
參數argc和argv是由main()傳遞的參數個數和內容。
參數 optstring為選項字串, 告知 getopt()可以處理哪個選項以及哪個選項需要參數。
如果選項字串裡的字母后接著冒號“:”,則表示還有相關的參數,全域變數optarg 即會指向此額外參數。
如果在處理期間遇到了不符合optstring指定的其他選項getopt()將顯示一個錯誤訊息,並將全域變數optarg設為“?”字元。
如果不希望getopt()印出錯資訊,則只要將全域變數opterr設為0即可。
getopt() 所設定的全域變數包括:
optarg——指向當前選項參數(如果有)的指標。 optind——再次調用 getopt() 時的下一個 argv 指標的索引。 optopt——最後一個已知選項。
#include<stdio.h>#include<stdlib.h>#include<unistd.h>int main(int argc,char *argv[]){int opt;while((opt = getopt(argc,argv,":if:lr")) != -1){switch(opt){case 'i':case 'l':case 'r':printf("option : %c \n",opt);break;case 'f':printf("filename : %s\n",optarg);break;case ':':printf("option needs a value\n");break;case '?':printf("Unknow option : %c\n",optopt);break;}}for(;optind < argc;optind++){printf("Argument: %s\n",argv[optind]);}exit(0);}
./args -i -lr 'hi there ' -f fred.c -q
option:i
option: l
option:r
filename: fred.c
unknow option:q
argument: hi there