发信人: tcpip (俺的昵称改了), 信区: cnunix
标  题: 容易忽视的函数和调用(四)
发信站: 哈工大紫丁香 (Sun Sep 26 15:46:47 1999), 转信

发信人: cpu (奔腾的心), 信区: Solaris
发信站: 华南网木棉站 (Thu Oct  8 16:38:13 1998), 转信

NAME
     getopt - get option letter from argument vector

SYNOPSIS
     #include <stdlib.h>

     int getopt(int argc, char * const *argv,
          const char *optstring);

     extern char *optarg;
     extern int optind, opterr, optopt;

这是个什么函数呢?如果泥想把命令行的输入选项做得比较unix,
象tar -xvf ...的风格,就用这个函数来parse命令行参数吧。大
概解释一下这个函数,最好自己看man。

argc是要分析的选项串指针数组argv的长度;argv[]是要分析的选
项串序列;optstring是选项字母集合,比如tar命令里的xvf三个字
母全都是,那么optstring至少是"xvf",如果某个选项字母后面跟
有冒号,那么表明这个选项字母后应该跟有一个参数。比如命令

        command -a -b paramb -cde

那么b选项后面的paramb就是b的参数,optstring为"ab:cde"。

getopt返回argv中的下一个选项,外部变量optind被置为下一个要
被处理的argv数组下标,初始化为1;当遇到不能解释的选项时,会
向标准出错提示?,这个可以设置外部变量opterr为0来disable掉,
此时引起出错的选项被写入optopt;当遇到某个有参数的选项时,
optarg会指向该参数;当argv的parse完成,返回EOF。

这样解释很容易晕倒98,还是给个感性认识吧,从man里头抄个例子。

     The following code fragment shows how one might process  the
     arguments for a command that can take the mutually exclusive
     options a and b, and the option o, which requires  an  argu-
     ment:

     #include <stdlib.h>
     #include <stdio.h>
     main (int argc, char **argv)
     {
          int c;
          extern char *optarg;
          extern int optind;
          int aflg = 0;
          int bflg = 0;
          int errflg = 0;
          char *ofile = NULL;

          while ((c = getopt(argc, argv, "abo:")) != EOF)
               switch (c) {
               case 'a':
                    if (bflg)
                         errflg++;
                    else
                         aflg++;
                    break;
               case 'b':
                    if (aflg)
                         errflg++;
                    else
                         bflg++;
                    break;
               case 'o':
                    ofile = optarg;
                    (void)printf("ofile = %s\n", ofile);
                    break;
               case '?':
                    errflg++;
               }
          if (errflg) {
               (void)fprintf(stderr,
                     "usage: cmd [-a|-b] [-o <filename>] files...\n");
               exit (2);
          }
          for ( ; optind < argc; optind++)
               (void)printf("%s\n", argv[optind]);
          return 0;
     }
--

        ******************************************************
                
               青岛啤酒,可能是世界上最好的啤酒 。。。 。。。

        ******************************************************

※ 修改:.trueip 于 Sep 26 15:50:34 修改本文.[FROM: dns.mtlab.hit.ed]
--
※ 转寄:.华南网木棉站 bbs.gznet.edu.cn.[FROM: dns.mtlab.hit.ed]

--
☆ 来源:.哈工大紫丁香 bbs.hit.edu.cn.[FROM: trueip.bbs@melon.gzn]
[百宝箱] [返回首页] [上级目录] [根目录] [返回顶部] [刷新] [返回]
Powered by KBS BBS 2.0 (http://dev.kcn.cn)
页面执行时间:2.365毫秒