Mike's blog

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  0 Posts :: 23 Stories :: 83 Comments :: 0 Trackbacks

常用链接

留言簿(17)

我参与的团队

搜索

  •  

最新评论

getopt()原型:
int getopt( int argc, char *const argv[], const char *optstring );
参数argc、argv分别对应main函数的参数,表示参数个数和参数数组,optstring为选项字符串。getopt函数调用会返回第一个选项,如果以相同的参数再次调用的话会返回下一个选项,以此类推,当参数列已经到结尾时getopt()函数返回-1,当遇到一个未知的选项时 getopt 返回'?',并且每次都会重新设置相应的全局变量。
getopt()设置的全局变量包括:
1.optarg(char*) -- 指向当前选项参数的指针;
2.optind(int)   -- 再次调用getopt()时的下一个argv指针的索引;
3.optopt(int)   -- 最后一次调用getopt()返回的已知选项;
4.opterr(int)   -- 变量opterr被初始化为1。如果不希望getopt()输出出错信息,将全域变量opterr设为0即可;
用一个自己应用到的例子来简单解析该函数:
 1 #include <stdio.h>
 2 #include <unistd.h>
 3 
 4 int main(int argc, char** argv )
 5 {
 6   int ch,destConsole = 0; 
 7   int def = 0;
 8   char* buf[4];
 9 
10   opterr = 0;
11   while ((ch = getopt(argc, argv, "Of:h:p:"))!= -1) {
12     switch(ch) {
13       case 'O':
14         buf[0= optarg;
15         break;
16       case 'f':
17         buf[1= optarg;
18         break;
19       case 'h':
20         buf[2= optarg;
21         break;
22       case 'p':
23         buf[3= optarg;
24         break;
25       default:
26         def = 1;
27     }   
28   }
29 
30   printf("buf[0]: %s\n", buf[0]);
31   printf("buf[1]: %s\n", buf[1]);
32   printf("buf[2]: %s\n", buf[2]);
33   printf("buf[3]: %d\n", atoi(buf[3]));
34 
35   return 0;
36 }

这是一个记录日志的程序部分代码(没做出错处理),同时支持终端输出、写文件、远程传输等功能(还有一些写数据库等,不一一列举)。
选项字符串为:“Of:h:p:”:
O表示是无参数选项,终端输出判断部分在14行,可以加一行给终端输出设置标记,比如destConsole=1,无参数自然对应30行就应该打印空;
f、h、p都为有参数选项,如果都有设置有效,那么对应的就会在31-33行分别打印文件名、主机名、端口号。
运行结果:
[root@develop-x /]# ./testOpt -O -f test.txt -h 192.168.0.111 -p 6666
buf[0]: 
buf[1]: test.txt
buf[2]: 192.168.0.111
buf[3]: 6666
复杂命令行处理getopt_long()可以参考man和getopt(),主要是增强了长选项的功能。
posted on 2008-10-14 15:56 老狼 阅读(2053) 评论(2)  编辑 收藏 引用 所属分类: C/C++

Feedback

# re: 使用getopt分析命令行参数 2008-11-29 12:43 蓝木
good!  回复  更多评论
  

# re: 使用getopt分析命令行参数 2008-11-29 12:44 蓝木
一直想要这个 可man一直没太看明白 谢谢LZ  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理