当前位置: 技术问答>linux和unix
getopt()函数
来源: 互联网 发布时间:2017-02-13
本文导语: /* te.c */ #include #include 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 flagn"); printf("%sn",optarg); break; case 't': printf("t flagn"); printf(...
/* te.c */
#include
#include
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 flagn");
printf("%sn",optarg);
break;
case 't':
printf("t flagn");
printf("%sn",optarg);
break;
}
}
}
gcc编译运行
$gcc te.c -o a
$./a -i test -t
然后输出为
i flag
nci
./a: option requires an argument -- 't'
也就是说根本就没有进入case 't':中去
求解释?
#include
#include
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 flagn");
printf("%sn",optarg);
break;
case 't':
printf("t flagn");
printf("%sn",optarg);
break;
}
}
}
gcc编译运行
$gcc te.c -o a
$./a -i test -t
然后输出为
i flag
nci
./a: option requires an argument -- 't'
也就是说根本就没有进入case 't':中去
求解释?
|
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.
这是最标准写法,先case : 解决缺少value的情况,再case ? 解决未知参数的情况,要求optstr以:开头即可
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.
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 operandn", optopt);
errflg++;
break;
case '?':
fprintf(stderr,
"Unrecognized option: -%cn", optopt);
errflg++;
}
}
这是最标准写法,先case : 解决缺少value的情况,再case ? 解决未知参数的情况,要求optstr以:开头即可
|
char optstr[]="i:t:";
多个:
改为char optstr[]="i:t";
意思不同
按照你的意思t后不跟参数能进入case 't':中去
多个:
改为char optstr[]="i:t";
意思不同
按照你的意思t后不跟参数能进入case 't':中去
|
试试加一个分支
case '?':
printf("flag %cn", optopt);
break;
case '?':
printf("flag %cn", optopt);
break;