使用getopt()处理命令行参数

时间:2022-04-10 11:32:30
假设有一程序 testopt,其命令行选项参数有:
  -i            选项
  -l            选项
  -r           选项
  -n <值> 带关联值的选项
则处理参数的代码如下:
#include <stdio.h>
#include <unistd.h> int main(int argc, char *argv[]) {
// 选项参数
int opt;
while ((opt = getopt(argc, argv, ":in:lr")) != -) {
switch (opt) {
case 'i': // 开关选项
case 'l':
case 'r':
printf("option: %c\n", opt);
break;
case 'n': // 提供供了所需关联值的选项
printf("value of option %c: %s\n", opt, optarg);
break;
case ':': // 缺乏所需关联值的选项,选项字符在全局变量 optopt 中
printf("option needs a value: %c\n", optopt);
break;
case '?': // 未知选项
printf("unknown option: %c\n", optopt);
break;
}
}
// 其余参数(非选项),由全局变量 optind 指出开始位置
while(optind<argc) {
printf("argument: %s\n", argv[optind]);
++optind;
}
return ;
}
输入命令行:
$ ./testopt abc.txt -il -r -p -n18 myfile.c xyz
输出:
option: i
option: l
option: r
unknown option: p
value of option n: 18
argument: abc.txt
argument: myfile.c
argument: xyz
可以看到,getopt()已经把命令行参数重新排序,非选项参数都挪到了后面。