#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 或 POSIX )返回 -1
(而不是 EOF
)当它完成处理选项时。全局变量 optind
是选项处理未使用的第一个参数的索引。
因此,当getopt()
返回 -1
, argv[optind]
包含一个指向非选项参数的指针,如果它不为空(或者,等效地,如果 optind < argc
)。
关于c - 无论如何要得到不是 unix C 选项的论点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49003409/