Chinaunix首页 | 论坛 | 博客
  • 博客访问: 162509
  • 博文数量: 24
  • 博客积分: 1205
  • 博客等级: 少尉
  • 技术积分: 160
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-21 13:41
个人简介

codeqq的ChinaUnix博客

文章分类

全部博文(24)

文章存档

2012年(1)

2011年(1)

2010年(4)

2009年(18)

我的朋友

分类: LINUX

2009-11-21 14:54:19

概述
 
这里主要是突出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) |
给主人留下些什么吧!~~