无论如何得到的论点不是unix C的选项

时间:2018-02-27 07:34:14

标签: c getopt

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>

int main(int argc, char **argv) {
    if(argc < 2) {
        printf("minimum one argument\n");
        return(1);
    } else {
        int o;
        int a = 1;
        int b = 1;

        while ((o = getopt(argc, argv, "a:b")) != -1) {
            switch (o) {
                case 'a' :
                    a = atoi(optarg);
                    break;
                case 'b' :
                    b = 0;
                    break;
                default :
                    printf("Error\n");
                    exit(1);
            }
        }
        printf("argument is %s, flag a is %d, flag b is %d\n", argv[3], a, b);
    }

}

这可以通过多种方式运行。 (调用file1.c以上)

$ gcc -Wall file1.c
$ ./a.out -a14 10
argument is 10, flag a is 14, flag b is 1

$ ./a.out -b 12
argument is 12, flag a is 1, flag b is 0

$ ./a.out 12
argument is 12, flag a is 1, flag b is 1

$ ./a.out -b -a12 15
argument is 15, flag a is 12, flag b is 0

我如何获得参数的索引位置,该参数不是一个选项,也可以使所有这些按预期工作?

0 个答案:

没有答案