GB | BIG5
|
| > 絪祘м砃 > C/C++ > タゅ |
 |
| ㏑︽把计だ猂 |
| http://linuxc.51.net/ :Hoyt (2001-08-22 16:41:41) |
龟悔祘ぇいи竒盽璶癸㏑︽把计秈︽だ猂. ゑиΤ祘a钡砛把计.薄猵琌
a -d print --option1 hello --option2 world
êи癸硂㏑把计秈︽だ猂?.竒盽ノㄧ计琌getopt㎝getopt_long.
#include <unistd.h>
#include <getopt.h>
int getopt(int argc,char const **argv, const char *optstring);
int getopt_long(int argc,char const **argc,
const char *optstring,const struct option *longopts,
int *longindex);
extern char *optarg;
extern int optind,opterr,optopt;
struct option {
char *name;
int has_flag;
int *flag;
int value;
};
getopt_long琌getopt耎甶.getopt钡㏑︽把计琌(-)秨繷,τgetopt_long临钡(--)秨繷把计.(-)秨繷把计夹вΤダ,τ(--)秨繷把计琌才﹃. -d,--option1匡兜.
argc,㎝argv把计琌mainㄧ计把计.optstringи钡把计.ㄤΑ:把计1[:]把计2[:].... ㄤい把计琌и钡把计,狦玙腹⊿Τ菠,êボ硂把计瞷ゲ惠璶盿把计. ゑoptstringabc:d:ボ硂把计匡兜a,b,c,dㄤいc,d瞷ゲ斗璶Τ把计.狦и块и⊿Τ矗ㄑ把计匡兜.╰参盢穦弧 ぃ粄醚 匡兜. getoptи﹚把计匡兜.盢把计玂optargい,狦竒だ猂ЧΘ┮Τ把计ㄧ计-1.硂optind獶匡把计秨﹍竚.
#include <stdio.h>
#include <unistd.h>
int main(int argc,char **argv)
{
int is_a,is_b,is_c,is_d,i;
char *a_value,*b_value,*c_value,temp;
is_a=is_b=is_c=is_d=0;
a_value=b_value=c_value=NULL;
if(argc==1)
{
fprintf(stderr,"Usage:%s [-a value] [-b value] [-c value] [-d] arglist ...\n",
argv[0]);
exit(1);
}
while((temp=getopt(argc,argv,"a:b:c:d"))!=-1)
{
switch (temp)
{
case 'a':
is_a=1;
a_value=optarg;
break;
case 'b':
is_b=1;
b_value=optarg;
break;
case 'c':
is_c=1;
c_value=optarg;
break;
case 'd':
is_d=1;
break;
}
}
printf("Option has a:%s with value:%s\n",is_a?"YES":"NO",a_value);
printf("Option has b:%s with value:%s\n",is_b?"YES":"NO",b_value);
printf("Option has c:%s with value:%s\n",is_c?"YES":"NO",c_value);
printf("OPtion has d:%s\n",is_d?"YES":"NO");
i=optind;
while(argv[i]) printf(" with arg:%s\n",argv[i++]);
exit(0);
}
getopt_longゑgetopt確馒翴,ぃ筁ノ硚璶ゑgetopt約獂.struct option и钡把计匡兜.
name:匡兜嘿(иoption1)
has_flag:0ボ⊿Τ把计,讽1硂把计匡兜璶钡把计.2ボ把计Τ⊿Τ.
ㄧ计.狦NULL,êval,玥0.盢longindex结匡兜┮计舱(longopts)竚.
/* 硂龟ㄒ琌眖 GNU Libc も */
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
int main (int argc, char **argv)
{
int c;
while (1)
{
struct option long_options[] =
{
{"add", 1, 0, 0},
{"append", 0, 0, 0},
{"delete", 1, 0, 0},
/* 才c,单 -c 匡兜 */
{"create", 0, 0, 'c'},
{"file", 1, 0, 0},
/* 计舱挡 */
{0, 0, 0, 0}
};
/* getopt_long stores the option index here. */
int option_index = 0;
c = getopt_long (argc, argv, "abc:d:",
long_options, &option_index);
/* Detect the end of the options. */
if (c == -1)
break;
switch (c)
{
case 0:
printf ("option %s", long_options[option_index].name);
if (optarg)
printf (" with arg %s\n", optarg);
break;
case 'a':
puts ("option -a\n");
break;
case 'b':
puts ("option -b\n");
break;
/* 琌-c --creat把计ㄓ */
case 'c':
printf ("option -c with value `%s'\n", optarg);
break;
case 'd':
printf ("option -d with value `%s'\n", optarg);
break;
}
}
exit (0);
}
讽и块岿粇匡兜,╰参穦倒岿粇矗ボ,狦и稱姜硂獺,и砞竚opterr0,癸岿粇匡兜,ㄧ计だ猂'?'才.и癸硂才秈︽矪瞶.
(http://www.fanqiang.com)
秈UNIX阶韭
|
|
| 闽ゅ彻 |
|
|
|
|
 |
」 荚眏 舧だㄉ 」 |