链接: https://www.cnblogs.com/qingergege/p/5914218.html.
自己测试
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
int iError;
int bList = 0;
//参数选项
while ((iError = getopt(argc, argv, "ls:f:h:d:")) != -1)
{
printf("optind: %d\n", optind);
switch(iError)
{
case 'l':
{
bList = 1;
break;
}
case 's':
{
printf("HAVE option: -s.\r\n");
printf("The argument of -s is %s\n\n", optarg);
break;
}
case 'f':
{
printf("HAVE option: -f.\r\n");
printf("The argument of -f is %s\n\n", optarg);
break;
}
case 'h':
{
printf("HAVE option: -h.\r\n");
printf("The argument of -h is %s\n\n", optarg);
break;
}
case 'd':
{
printf("HAVE option: -d.\r\n");
printf("The argument of -d is %s\n\n", optarg);
break;
}
default:
{
printf("Usage: %s -l\n", argv[0]);
return -1;
break;
}
}
}
//缺少参数
//bList==0,说明你输入的选项字符串中没有-l选项
/*
比如你输入命令: ./show -s 16 -f ./FZYTK.TFT
此时,argc == 5,optind == 5
(下一次将从5的位置开始搜索,但argv[5]为空,再次调用getopt()函数就会返回-1,循环随之结束。)
命令输入错误,缺少参数
比如你输入命令: ./show -s 16 -f ./FZYTK.TFT file.txt
此时,argc == 6,optind == 5
命令输入通过
显示正常
比如你输入命令: ./show -s 16 file.txt
此时,argc == 4,optind == 3
命令输入通过
但是显示不正常,因为没有指定字库信息
比如你输入命令: ./show file.txt
此时,argc == 2,optind == 1
命令输入通过
但是显示不正常,因为没有指定字库信息
比如你输入命令: ./show
此时,argc == 1,optind == 1
命令输入错误,缺少参数
optind这个值要特别留心,是存放下一次搜索的位置。
*/
if (!bList && (optind >= argc))//缺少参数
{
printf("false,optind=%d,argc=%d.\r\n", optind,argc);
return -1;
}
else
{
printf("optind=%d,argc=%d.\r\n", optind,argc);
return 0;
}
}