小默

getopt getopt_long

getopt
--man
        #include <unistd.h>

       int getopt(int argc, char * const argv[],
                  const char *optstring);

       extern char *optarg;
       extern int optind, opterr, optopt;

       #include <getopt.h>

       int getopt_long(int argc, char * const argv[],
                  const char *optstring,
                  const struct option *longopts, int *longindex);

--ex

 23 struct option longopts[] = {
 24     {"icmp", no_argument, NULL, 'i'},
 25     {"help", no_argument, NULL, 'h'},
 26     {"drop", required_argument, NULL, 'd'},
 27     {0,0,0,0}
 28 };

 51     while((c = getopt_long(argc, argv, "hid:", longopts, NULL))!=-1){
 52         switch(c){
 53             case 'i':{
 54                 own->icmp_off = 1;
 55                 break;
 56             }
 57             case 'd':{
 58                 own->drop_ip = inet_addr(optarg);
 59                 break;
 60             }
 61             case 'h':{
 62                 print_help(argv[0]);
 63                 return -1;
 64             }
 65             default:
 66                 break;
 67         }

--

作用:
解析输入的参数。

参数:
argc和argv是传入main的参数个数 和 参数列表。
"hid:"是-h -i -d 这样的选项;d后有冒号,表示-d选项有参数跟着。
longopts是struct option *,列出-h -i -d对应的长选项格式--help --icmp --drop

相关外部变量:
extern char *optarg; - 当前选项的参数字串

posted on 2011-01-26 14:34 小默 阅读(1725) 评论(2)  编辑 收藏 引用 所属分类: Language

评论

# re: getopt getopt_long 2011-02-12 14:59 butterinsect

getopt_long(argc, argv, ":l:", longopts, NULL)

‘l’前面的冒号如何解释
  回复  更多评论   

# re: getopt getopt_long 2011-03-02 21:24 小默

@butterinsect
不知道= =!  回复  更多评论   


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


导航

统计

留言簿(13)

随笔分类(287)

随笔档案(289)

漏洞

搜索

积分与排名

最新评论

阅读排行榜