概述
这里主要是突出getopt()函数如何来获得命令行的非选项的那些字符或字符串,如:
$./command -d this is other words
假设-d选项是我们会在命令中接收的,而"this is oter words"不属于-d的参数,我们将在下面的程序中讨论怎么提取它们,并放入一个新的空间中...
处理这些串在某些情况下是必须的,比如tcpdump中,除了选项外,你还可以输入"tcp or udp"等类似语句,这是将传递给BPF的过滤规则,它们将被单独提取出来,再转换。(这段可不必了解)
讲几个参数:
optind:是在argv中第一个不是选项的元素,也就是argv[optind]就代表第一个不为选项的元素,如上面的"this",在经过switch之后,所有的非选项字符都被放在argv的后面,所以可以连续输出,如上面命令可等价于:
$./command this is -d other words
这两句是等价的,在switch之后,-d依然放在this之前,这使得我们能很容易的取出所有的非选项值。
optarg:存放选项对应的参数(如果选项需要有参数的话)
代码
/* * getopt()---HOW-TO * zuii 2008/09/25 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h>
/* Function usage(),the -h option */ void usage() { printf("Usage:I don't know how to use it! \n"); exit(0); }
int main(int argc,char **argv) { char c; int count=0; char **p,*src; char *buf,*dst;
while((c=getopt(argc,argv,"hdt:"))!=-1){ switch(c){ case 'h': usage(); break; case 'd': printf("This is d option,no argument\n"); break; case 't': printf("The t option,argument is: %s \n",optarg); break; default: printf("foo? bar?I don't know!\n"); } }
/*The number of words which are not options */ count=argc-optind;
/* Allocate a space for new string */ buf=(char *)malloc(count*sizeof(*p)); if(buf==NULL) { printf("Malloc error\n"); exit(1); }
/* p--point to the first word we want */ p=argv+optind;
/* dst--point to the new space */ dst=buf;
/* Copy from src(argv) to dst(buf) */ while((src=*p++)!=NULL) { /* get one word in the cycle below */ while((*dst++=*src++)!='\0') ; dst[-1]=' '; } dst[-1]='\0';
printf("%s\n",buf); return 0; }
|
编译执行
zuii@william-desktop:~/c$ gcc -Wall getoption.c -o getoption zuii@william-desktop:~/c$ ./getoption this -d is -t foo other words This is d option,no argument The t option,argument is: foo this is other words zuii@william-desktop:~/c$
|
阅读(439) | 评论(0) | 转发(0) |