首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

getopt()函数解决办法

2012-04-11 
getopt()函数/* te.c */#include stdio.h#include unistd.hvoid main(int argc, char **argv){int cc

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++;                      }                  } 

热点排行
Bad Request.