getopt -- 用来解析命令行选项参数

链接: 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;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值