c getopt函数用法

时间:2021-09-20 23:14:26
 #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, "bp:r:")) != -1)        
	printf("The argument of -b is %s\n", optarg);
        switch (ch) {
        case 'b':
            printf("HAVE option: -b\n");
            aflag = 1;
            break;
        case 'p':
            printf("HAVE option: -p\n");
            bflag = 1;
            break;
        case 'r':
            printf("HAVE option: -r");
            cflag = 1;
            break;
        case '?':
            printf("Unknown option: %c\n",(char)optopt);
            break;     }
} 



输出:


pateo@pateo-B86N53X:~/work/study$ ./test -b liao -p jian -r guo
HAVE option: -b
The argument of -b is (null)
HAVE option: -p
The argument of -b is jian
HAVE option: -r
The argument of -b is guo
pateo@pateo-B86N53X:~/work/study$ 


说明:

1.单个字符,表示选项,
2.单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧 跟在选项后或者以空格隔开。该参数的指针赋给optarg。
3 单个字符后跟两个冒号,表示该选项后必须跟一个参数。参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。(这个特性是GNU的扩张)。