星期二, 2月 28, 2006

C function : getopt

標頭檔: unistd.h ( 也有單純的 getopt.h )

原型:
int getopt(int argc, char * const argv[], const char *optstring);
說明:
用來分析命令列參數,開頭的兩個argument剛好跟 program argument一樣。
參數 optstring 是有效選項(字母)。如 " a:bf"。代表要接受的option有 -a, -b, -f。
其中option a的後面是":"號,代表-a option後還有參數(例如-aext2)。
getopt提供兩個global variable : optarg,optopt。用來輔助getopt這個function。
像a:這樣的參數,getopt會將-a後面的字串放到optarg中。
範例:
#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv)
{
int ch;

while((ch=getopt(argc,argv,"a:cf"))!=-1)
switch(ch)
{
case 'a':
printf("choose a: %s\n",optarg);
break;
case 'c':
printf("option c\n");
break;
case 'f':
printf("option f\n");
break;
}
}

沒有留言:

網誌存檔