這個東西比較有用,
以后可以用它來直接讀了。
#include <unistd.h>
#include <stdio.h>
int main(int argc, char * argv[])
{
int aflag=0, bflag=0, cflag=0;
int ch;
while ((ch = getopt(argc, argv, "ab:c")) != -1)
{
printf("optind: %d\n", optind);
switch (ch) {
case 'a':
printf("HAVE option: -a\n");
aflag = 1;
break;
case 'b':
printf("HAVE option: -b\n");
bflag = 1;
printf("The argument of -b is %s\n", optarg);
break;
case 'c':
printf("HAVE option: -c");
cflag = 1;
break;
case '?':
printf("Unknown option: %c\n",(char)optopt);
break;
}
}
}
int getopt( int argc, char *const argv[], const char *optstring );
給定了命令參數的數量 (argc
)、指向這些參數的數組 (argv
) 和選項字符串 (optstring
) 后,getopt()
將返回第一個選項,并設置一些全局變量。使用相同的參數再次調用該函數時,它將返回下一個選項,并設置相應的全局變量。如果不再有識別到的選項,將返回 -1
,此任務就完成了。
getopt()
所設置的全局變量包括:
optarg
——指向當前選項參數(如果有)的指針。
optind
——再次調用 getopt()
時的下一個 argv 指針的索引。
optopt
——最后一個已知選項。
./getopt -a -d -b foo
optind: 2
HAVE option: -a
./getopt: invalid option -- d
optind: 3
Unknown option: d
optind: 5
HAVE option: -b
The argument of -b is foo