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

Anyway to get the argument that isn't an option unix C

#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

如何获取不是选项的参数的索引位置并使所有这些都按上面的预期工作?

getopt() 函数 (GNU or POSIX) returns -1(而不是 EOF)当它完成处理选项时。全局变量 optind 是选项处理未使用的第一个参数的索引。

因此,当 getopt() returns -1 时,argv[optind] 包含指向 non-option 参数的指针,如果它不为空(或者,等价地,如果 optind < argc).