今天早早地起床,看了一下最近一直想看的c命令行解析,之前在《c和指针》上已经将argc和argv了解了,今天主要的目标是getopt() getopt_long这两个库函数,以下是根据网上一哥们的笔记写的两个小程序
[root@bjxdurs235 20091122]# jobs
[1]- Stopped vim my_getopt.c
[2]+ Stopped vim my_getopt_long.c
[root@bjxdurs235 20091122]# cat -n my_getopt.c
1 #include
2 #include
3
4 int main(int argc , char **argv)
5 {
6
7 int op;
8 char *my_optarg;
9
10 opterr = 0;
11 while( ( op = getopt( argc, argv, "ngl:" ) ) != -1 ){
12 switch(op){
13 case 'n':
14 printf("my name is : liufeng\n");
15 break;
16 case 'g':
17 printf("my girlfriend name is : zhangning\n");
18 break;
19 case 'l':
20 my_optarg = optarg;
21 printf("Our love is : %s\n",my_optarg);
22 break;
23 case '?':
24 fputs("argumnet error !\n",stderr);
25 break;
26
27 }
28
29 }
30 printf("optind:%d\n",optind);
31
32 return 0;
33
34 }
[root@bjxdurs235 20091122]# cat -n my_getopt_long.c
1 #include
2 #include
3
4 int do_name, do_gf_name;
5 char *l_opt_arg;
6
7 struct option longopts[] = {
8 { "name", no_argument, &do_name, 1 },
9 { "gf_name", no_argument, &do_gf_name, 1 },
10 { "love", required_argument, NULL, 'l' },
11 { 0, 0, 0, 0},
12 };
13
14 int main(int argc, char *argv[])
15 {
16 int c;
17 opterr = 0;
18 while((c = getopt_long(argc, argv, "l:", longopts, NULL)) != -1){
19 switch (c){
20 case 'l':
21 l_opt_arg = optarg;
22 printf("Our love is %s!\n", l_opt_arg);
23 break;
24 case 0:
25 printf("getopt_long() set env :do_name = %d\n", do_name);
26 printf("getopt_long() set env :do_gf_name = %d\n", do_gf_name);
27 break;
28 case '?':
29 fputs("argumnet error!\n",stderr);
30 break;
31 }
32 }
33 return 0;
34 }
35
程序主体转载自:http://blog.chinaunix.net/u2/82009/showart_1888571.html
自己写完后,虽然比较简单,但是比纯粹地看别人的代码,还是加深了理解,看的时候更容易理解了
阅读(681) | 评论(0) | 转发(0) |