getopt的详细用法


int main(int argc, char *argv[])主函数中具有两个参数,整形argc和字符指针argv。

argc  ------- 命令行参数的总个数,包括执行的程序名称。

argv[i] ------- 表示第i个参数,argv[0]就是执行的程序名称。

例子:

#include<stdio.h>
#include<unistd.h>
int main(int argc, int *argv[])
{
      int i ;
      printf("argc is %d\n",argc);
      for(i=0;i<argc;i++)printf("argv[%d] is %s\n",i,argv[i]);
}

编译后文件名为test,输出结果:


getopt 是一个分析命令行函数,在表头文件<unistd.h>中,一般是在UNIX系统下使用。

定义的函数为:int getopt(int argc, char const *argv[],const char * optstring);

optstring是getopt()的短参数列表,如“abc:d::”。

上面的a为不带值得参数;b是必须带值得参数,因为参数后面多加了一个冒号;而c则是可选值得参数,它后面加了两个冒号。

实际调用的时候,“-a -b -c cvalue -ddvalue”这样用,不带值得参数可以连写,如"-ab",参数部分先后顺序,但是要记得可选值参数的值和参数之间不能有空格,例如d参数。

getopt的全局变量

optarg ------- 指向当前参数所带的值的指针

optind -------- 再次调用getopt()时下个argv指针的索引

optopt -------- 最后一个未知的选项

参考百度百科的实例:

#include<stdio.h>
#include<unistd.h>
int main(int argc,char **argv)
{
int ch;
opterr = 0;
while((ch = getopt(argc,argv,”a:bcde”))!= -1)
{
switch(ch)
{
case ‘a’: printf(“option a:’%s’\n”,optarg); break;
case ‘b’: printf(“option b :b\n”); break;
default: printf(“other option :%c\n”,ch);
}
printf(“optopt +%c\n”,optopt);
}
}
执行 $./getopt –b
option b:b
执行 $./getopt –c
other option:c
执行 $./getopt –a
other option :?
执行 $./getopt –a12345
option a:’12345’

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值