使用getopt()函数解析命令行参数;第三个参数optstring要特别注意。
optstring说明:
- 单字符选项,a,参数后无冒号
- 参数与值之间用空格隔开,b:,参数后接一个冒号
- 参数与值无空格,D::,参数后接两个冒号
#include <unistd.h>
#include <stdio.h>
// 测试参数 -a -b 100 -Dhello
int main(int argc, char **argv)
{
int opt;
// 三种参数类型 a -a不带参数,b: -b 空格带参数,D:: -D 无空格直接接参数
while ((opt = getopt(argc, argv, "ab:D::")) != -1)
{
switch (opt)
{
case 'a':
printf("this is a\r\n");
break;
case 'b':
printf("this is b arg %s\r\n", optarg);
break;
case 'D':
printf("this is D arg %s\r\n", optarg);
break;
default:
printf("this is %c\r\n", opt);
break;
}
}
}