C语言之getopt使用

在使用开源的程序时,随处可见程序可以接受输入的参数,比如著名的压测工具ab,使用的时候就可以输入如下命令:ab -c 100 -n 10000 http://www.37.com。这样就可以吧客户端数和压测次数传递给ab程序。在c语言中,可以使用int main(int argc,char* argv[]),来获取参数。但是,使用argc和argv这2个变量,有一个缺点,就是需要写大量的代码解析程序参数,其实,在linux下可以使用getopt这个接口来获取参数。

getopt接口:

#include <unistd.h>

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

extern char *optarg;
extern int optind, opterr, optopt;


getopt参数解析:

argc:就是main的形参argc

argv:就是main的形参argv

optstring:选项字符串,一个字母表示一个短参数,如果字母后带有“:”,表示这个参数必须带有参数。如"c:n:a",则程序可以接受参数"-c 100 -n 1000 -a"

optarg变量:用于获取传入的参数值(如果有)

optind变量:argv的当前索引值。当getopt()在while循环中使用时,循环结束后,剩下的字串视为操作数,在argv[optind]至argv[argc-1]中可以找到。

opterr变量:这个变量非零时,getopt()函数为“无效选项”和“缺少参数选项,并输出其错误信息。

optopt变量:当发现无效选项字符之时,getopt()函数或返回'?'字符,或返回':'字符,并且optopt包含了所发现的无效选项字符。

PS:默认情况下,如果参数错误getopt接口会输出错误参数信息,如果要使用自定义的错误信息,可以将opterr设置为0。


getopt接口可以处理短参数,处理长参数,就要使用getopt_long接口。

getopt_long(int argc,char * const argv[],const char * shortopts,const struct option *longopts,int *longindex)
下面介绍各个参数的含义:
argc、argv是main函数的两个同名的参数。
shortopts选项字符串,一个字母表示一个短参数,如果字母后带有“:”,表示这个参数必须带有参数。如"c:n:a",则程序可以接受参数"-c 100 -n 1000 -a"
longopts是一个struct option结构体的数组,option结构体的定义如下:

struct option{ 
         const char *name; 
         int has_arg; 
         int *flag; 
         int val; 
};

name是长选项的名字,has_arg值为0、1、2,分别表示没有参数、有参数、参数可选,flag如果为NULL,函数返回val的值,否则将val的值写入flag指向的变量中,一般情况下,如果flag为NULL,则val的值为该长选项对应的短选项。

longindex参数如果没有设置为NULL,那么它就指向一个变量,这个变量会被赋值为寻找到的长选项在longopts中的索引值,这可以用于错误诊断。

/*
 * getopt测试
 * 目标:
 * 1)程序能接受长参数--number和短参数-n,并打印
 * 2)程序能接受长参数--client和短参数-c,并打印
 */
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
//header for getopt
#include<unistd.h>
//header for getopt_long
#include <getopt.h>

static const struct option long_options[] = {
		{"number",1,NULL,'n'},
		{"clients",1,NULL,'c'}
};

void usage(void);
int main(int argc,char* argv[])
{
	//getopt返回值
	int opt=0;
<span style="white-space:pre">	opterr=0;//关闭getopt错误信息</span>
	while((opt=getopt_long(argc,argv,"n:c:",long_options,NULL))!=-1)
	{
		//optarg is global
		switch(opt)
		{
			case 'n':
				printf("The number is %s\n",optarg);
				break;
			case 'c':
				printf("The clients is %s\n",optarg);
				break;
			default:
				//非法参数处理,也可以使用case来处理,?表示无效的选项,:表示选项缺少参数
				usage();
				exit(1);
				break;

		}
	}
	printf("done!\n");
	return 0;
}

void usage(void)
{
	printf("Argument error!\n");
}


  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C语言getopt()函数用于分析命令行参数。它的声明为: int getopt(int argc, char * const argv[], const char * optstring); 该函数通过解析命令行参数来获取选项和参数的值。用户可以在命令行中使用不同的选项来传递参数给程序。 下面是一个getopt()函数的示例代码: #include <unistd.h> #include <stdio.h> int main(int argc, char * argv[]){ int i; printf("%s\n","argv原序:"); for(i = 0;i < argc;i++){ printf("%s ",argv[i]); } printf("\n"); printf("START@optind:%d,opterr:%d\n",optind,opterr); int ret; while((ret = getopt(argc,argv,"aW;b:c:de::")) != -1){ switch(ret){ case 'a': printf("Having option -a\n"); break; case 'b': printf("having option -b,and its argument is %s\n",optarg); break; case 'c': printf("having option -c,and its argument is %s\n",optarg); break; case 'd': printf("Having option -d\n"); break; case 'e': printf("having option -e,it is optional,and its argument is %s\n",optarg); break; case '?': printf("Unknown option -%c\n",(char)optopt); break; } } printf("END@optind:%d,argv[%d]:%s\n",optind,optind,argv[optind]); printf("%s\n","argv现序:"); for(i = 0;i < argc;i++){ printf("%s ",argv[i]); } printf("\n"); return 0; } 该示例演示了如何使用getopt()函数解析命令行参数。程序通过指定选项和参数的形式来接受用户输入,并根据不同的选项执行不同的操作。在示例中,选项包括:a、b、c、d和e,其中e选项是可选的。通过在命令行中输入相应的选项和参数,程序会根据不同的选项执行相应的代码逻辑。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [C语言getopt()函数和select()函数的使用方法](https://download.csdn.net/download/weixin_38621104/14868224)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [C语言——getopt函数](https://blog.csdn.net/weixin_40763897/article/details/87898328)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值