百度空间 | 百度首页 
 
查看文章
 
getopt函数的例子
2008-11-24 00:10
打算重新拿起webalizer的源代码来看看,以前看明白的东西忘得差不多了!现在记下来!

getopt是用来解析命令行参数的一个函数!

#include <unistd.h> /*for getopt*/
#include <stdlib.h> /*for exit()*/
#include <stdio.h> /*for printf*/

int
main(int argc, char *argv[])
{
    int opt;
    opterr = 0;
   

    while ((opt = getopt(argc, argv, "nt:")) != -1) {
        switch (opt) {
        case 'n':
            printf("there is a option 'n',and it's args is %s\n", optarg);
            printf("optind = %d\n", optind);
            break;
        case 't':
            printf ("t and t's args is %s\n", optarg);
            printf("optind = %d\n", optind);
            break;
        //default: /* '?' */
        case '?':
            fprintf(stderr, "Usage: %s [-t nsecs] [-n]\n",argv[0]);
            fprintf(stderr,"invalid option %c\n", optopt);
            exit(1);
        }
    }
    printf("%d\n",optind);

    return 0;
}

仔细的文档看man 3 getopt
有几个extern 变量看看是什么意思:
optind 下一个选项的索引,这个值是不会是某个选项的参数在argv[]中的索引!getopt就是用他来遍历argv的!

optarg,如果当前选项有参数的话optarg指向些string,没有的话,optart=NULL;

opterr,如果argv中有一个getopt不认识的选项,不在那个 optstring(即getopt的第三个参数)中getopt会出错,这时候getopt返回'?',并把这个选项赋给了optopt,并在stderr有输出.
如果你把opterr赋成0,则不会有输出!还是会返回'?',还是会optopt=那个不认识的选项字符!


需要补充说明一点的是Linux下一个命令通常带选项和参数支持短格式和长格式两种。
短格式比如:
command -h #这就是这个命令只有一个选项h,并且h不带任何参数
对应的长格式比如:
command --help #这就是这个命令只有一个选项help,并且help不带任何参数
如果一个选项带有参数,那称之为选项参数,比如:
command -f filename #这就是这个命令只有一个选项f,并且f需要带参数表明文件名
对应的长格式可能是:
command --filename yourfilename #这就是这个命令只有一个选项filename,并且f需要带参数表明文件名


还有两个相似的函数getopt_long,getopt_long_long!
接着man 去!

类别:gnu/linux | 添加到搜藏 | 浏览() | 评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu