Getopt:命令行解析函数

 

涉及到名词:命令+选项+选项参数+操作数

# cat  -n  10  /etc /passwd

cat是命令名,-n是选项,10是选项参数,/etc/passwd是操作数。

函数原型:

       int getopt(int argc, char * const argv[], const char *optstring);

       extern char *optarg;

       extern int optind, opterr, optopt;


 

opterr,默认是非零1,如果调用出错时看opterr的值,如果非零就打印错误信息。若果是0就不打印。所以可以在调用前设置opterr=0,抑制getopt内部的错误信息的输出。

optopt,当调用选项在optstring中没有时,opt存放该invalid选项;另外,要是optstring字串中后面接冒号的需要选项参数的选项在调用时没有选项参数,则optopt保存该missing argument的选项。

optarg,当选项需要选项参数时,选项参数会保存在optarg中。

optind,index 下标值,本次调用后argv数组中第一个非选项(包含选项参数)的下标值。

返回值:

1、         正常情况返回解析出来的选项字符,optstring解析完后返回-1。

2、        Invalid参数返回’?’。

3、        Missing argument返回依赖于optstring字串的首字符是否为冒号,如果是冒号则返回冒号,否则返回’?’。

为了便于区分是invalid还是missing argument,建议optstring以冒号开头。

 

例程:

#include <stdio.h>
#include <getopt.h>

int main(int argc, char **argv)
{
	char result;
	//opterr = 0;
	while(-1 != (result = getopt(argc, argv, ":ln:q:m:")))
	{
		switch(result)
		{
			case 'l':
				printf("This option is 'l'\n");
				break;
			case 'n':
				printf("This option is 'n' which need argument %s\n", optarg);
				break;
			case 'q':
				printf("This option is 'q' which need argument %s\n", optarg);
				break;
			case 'm':
				printf("This option is 'm' which need argument %s\n", optarg);
				break;
			case '?':
				printf("Optioin '%c' is a unknown argument\n", (char)optopt);
				break;
			case ':':
				printf("Option '%c' missing a argument\n", (char)optopt);
				break;
			default:
				break;
		}
	}

	return 0;
}


运行结果:

[root@localhost test]# ./a.out -n
Option 'n' missing a argument
[root@localhost test]# ./a.out -m
Option 'm' missing a argument
[root@localhost test]# ./a.out -l
This option is 'l'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值