日期:2014-05-16  浏览次数:20686 次

getopt()函数
/* te.c */
#include <stdio.h>
#include <unistd.h>
void main(int argc, char **argv){
int c;
char optstr[]="i:t:";
while((c=getopt(argc,argv,optstr))!=-1){
switch(c){
case 'i':
printf("i flag\n");
printf("%s\n",optarg);
break;
case 't':
printf("t flag\n");
printf("%s\n",optarg);
break;
}
}
}

gcc编译运行
$gcc te.c -o a
$./a -i test -t
然后输出为
i flag
nci
./a: option requires an argument -- 't'
也就是说根本就没有进入case 't':中去
求解释?

------解决方案--------------------
char optstr[]="i:t:";
多个:
改为char optstr[]="i:t";
意思不同
按照你的意思t后不跟参数能进入case 't':中去
------解决方案--------------------
试试加一个分支

case '?':
printf("flag %c\n", optopt);
break;

------解决方案--------------------
RETURN VALUE
The getopt() function shall return the next option character specified on the command line.

A colon ( ':' ) shall be returned if getopt() detects a missing argument and the first character of optstring was a colon ( ':' ).

A question mark ( '?' ) shall be returned if getopt() encounters an option character not in optstring or detects a missing argument and the first character of
optstring was not a colon ( ':' ).

Otherwise, getopt() shall return -1 when all command line options are parsed.


C/C++ code
                  while ((c = getopt(argc, argv, ":abf:o:")) != -1) {
                      switch(c) {
                      case 'a':
                          if (bflg)
                              errflg++;
                          else
                              aflg++;
                          break;
                      case 'b':
                          if (aflg)
                              errflg++;
                          else {
                              bflg++;
                              bproc();
                          }
                          break;
                      case 'f':
                          ifile = optarg;
                          break;
                      case 'o':
                          ofile = optarg;
                          break;
                          case ':':       /* -f or -o without operand */
                                  fprintf(stderr,
                                          "Option -%c requires an operand\n", optopt);
                                  errflg++;
                                  break;
                      case '?':
                                  fprintf(stderr,
                                          "Unrecognized option: -%c\n", optopt);
                          errflg++;
                      }
                  }