這個(gè)東西比較有用,
以后可以用它來直接讀了。
#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 );
給定了命令參數(shù)的數(shù)量 (argc
)、指向這些參數(shù)的數(shù)組 (argv
) 和選項(xiàng)字符串 (optstring
) 后,getopt()
將返回第一個(gè)選項(xiàng),并設(shè)置一些全局變量。使用相同的參數(shù)再次調(diào)用該函數(shù)時(shí),它將返回下一個(gè)選項(xiàng),并設(shè)置相應(yīng)的全局變量。如果不再有識(shí)別到的選項(xiàng),將返回 -1
,此任務(wù)就完成了。
getopt()
所設(shè)置的全局變量包括:
optarg
——指向當(dāng)前選項(xiàng)參數(shù)(如果有)的指針。
optind
——再次調(diào)用 getopt()
時(shí)的下一個(gè) argv 指針的索引。
optopt
——最后一個(gè)已知選項(xiàng)。
./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