C语言中使用库函数解析命令行参数

在编写需要命令行参数的C程序的时候,往往我们需要先解析命令行参数,然后根据这些参数来启动我们的程序。

C的库函数中提供了两个函数可以用来帮助我们解析命令行参数:getopt、getopt_long。

getopt可以解析短参数,所谓短参数就是指选项前只有一个“-”(如-t),而getopt_long则支持短参数跟长参数(如"--prefix")。

 

getopt函数

#include<unistd.h>
int getopt(int argc,char * const argv[],const char *optstring);
extern char *optarg; //当前选项参数字串(如果有) extern int optind; //argv的当前索引值

各参数的意义:

argc:通常为main函数中的argc

argv:通常为main函数中的argv

optstring:用来指定选项的内容(如:"ab:c"),它由多个部分组成,表示的意义分别为:

1.单个字符,表示选项。

2 单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。

3 单个字符后跟两个冒号,表示该选项后可以跟一个参数,也可以不跟。如果跟一个参数,参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。

 

调用该函数将返回解析到的当前选项,该选项的参数将赋给optarg,如果该选项没有参数,则optarg为NULL。下面将演示该函数的用法

 1 #include <stdio.h>
 2 #include <unistd.h>
 3 #include <string.h>
 4 
 5 int main(int argc,char *argv[])
 6 {
 7     int opt=0;
 8     int a=0;
 9     int b=0;
10     char s[50];
11     while((opt=getopt(argc,argv,"ab:"))!=-1)
12     {
13         switch(opt)
14         {
15             case 'a':a=1;break;
16             case 'b':b=1;strcpy(s,optarg);break; 
17         }
18     }
19     if(a)
20         printf("option a\n");
21     if(b)
22         printf("option b:%s\n",s);
23     return 0;
24 }
View Code

编译之后可以如下调用该程序

 

getopt_long函数

与getopt不同的是,getopt_long还支持长参数。

#include <getopt.h>
int getopt_long(int argc, char * const argv[],const char *optstring,const struct option *longopts, int *longindex);

前面三个参数跟getopt函数一样(解析到短参数时返回值跟getopt一样),而长参数的解析则与longopts参数相关,该参数使用如下的结构

struct option {
  //长参数名
  const char *name;
  /*
    表示参数的个数
    no_argument(或者0),表示该选项后面不跟参数值
    required_argument(或者1),表示该选项后面一定跟一个参数
    optional_argument(或者2),表示该选项后面的参数可选
  */
  int has_arg;
  //如果flag为NULL,则函数会返回下面val参数的值,否则返回0,并将val值赋予赋予flag所指向的内存
  int *flag;
  //配合flag来决定返回值
  int val;
};

参数longindex,表示当前长参数在longopts中的索引值,如果不需要可以置为NULL。

下面是使用该函数的一个例子

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <getopt.h>
 4 
 5 int learn=0;
 6 static const struct option long_option[]={
 7    {"name",required_argument,NULL,'n'},
 8    {"learn",no_argument,&learn,1},
 9    {NULL,0,NULL,0}
10 };
11 
12 int main(int argc,char *argv[])
13 {
14     int opt=0;
15     while((opt=getopt_long(argc,argv,"n:l",long_option,NULL))!=-1)
16     {
17         switch(opt)
18         {
19             case 0:break;
20             case 'n':printf("name:%s ",optarg);                             
21         }
22     }
23     if(learn)
24         printf("learning\n");
25 }
View Code

编译之后可以如下调用该程序

转载于:https://www.cnblogs.com/runnyu/p/4943704.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值