免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1659 | 回复: 0
打印 上一主题 下一主题

一个例子讲解getopt()函数使用 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-11-21 14:54 |只看该作者 |倒序浏览
概述

这里主要是突出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$


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/106533/showart_2099998.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP