Glib解析命令行参数


#include <stdio.h>
#include <glib.h>

 
static gint max_user = 20;
static gint time_out = 2;
static gint listen_port = 8852;
static gchar listen_ip[32] = {"0.0.0.0"};
 
static gboolean debug = FALSE;
 
 
 
static GOptionEntry entries[] =
{
    {
        "listen",               /*参数长名*/
        'l',                    /*短参数名*/
        0,                      /*falg*/
        G_OPTION_ARG_STRING,    /*参数类型*/
        listen_ip,              /*参数变量*/
        "Set lisetn ip",        /*选项说明*/
        "listen_ip"             /*参数选项占位符说明*/
    },
 
    {"port",'p',0,G_OPTION_ARG_INT,
    &listen_port,"listen port","port"},
 
 
    {"max_user",'m',0,G_OPTION_ARG_INT,
    &max_user,"Define the max user for server","M"},
 
    {"time_out",'t',0,G_OPTION_ARG_INT,
     &time_out,"Stop connection when idel time over N","N"},
 
    {"debug",'d',0,G_OPTION_ARG_NONE,
    &debug,"Debug mode",NULL},
 
};
 
 
 
int main(int argc ,char **argv)
{
    GError *error = NULL;
    GOptionContext *context = NULL;
 
    context = g_option_context_new("-test tree model performance");
 
    g_option_context_add_main_entries(context,entries,NULL);
 
 
    // 扩展的选项
    //context 自带help选项,支持 --help,-h,-?,--help-all, 可以通过设置去掉
    //g_option_context_set_help_enabled(context,FALSE);
    //忽略错误的选项,有错误的选项默认会报错,忽略掉就不报错
    //g_option_context_set_ignore_unknown_options(context,TRUE);
    // help 里面打上一段文字说明,可以搞点版本号,版权说明什么的
    g_option_context_set_summary(context," Glib Test by Andy\n mhpmii@126.com\n");
 
    if(!g_option_context_parse(context,&argc,&argv,&error)) {
        g_print("option parseing failed : %s\n",error->message);
        return -1;
    }
 
    g_option_context_free(context);
 
    g_print("The Server Run at %s:%d\nmax uer :%d ,time out : %d  debug[%s]\n",
            listen_ip,
            listen_port,
            max_user,
            time_out,
            debug?"TRUE":"FALSE");
 
    return 0;
}
 
/***************************************/
// 其他说明
/***************************************/
//[1] flag 一般不需设置,填0
/*
typedef enum
{
  G_OPTION_FLAG_HIDDEN		= 1 << 0,   //设置选项不在--help中显示
  G_OPTION_FLAG_IN_MAIN		= 1 << 1,
  G_OPTION_FLAG_REVERSE		= 1 << 2,
  G_OPTION_FLAG_NO_ARG		= 1 << 3,
  G_OPTION_FLAG_FILENAME	= 1 << 4,
  G_OPTION_FLAG_OPTIONAL_ARG    = 1 << 5,
  G_OPTION_FLAG_NOALIAS	        = 1 << 6
} GOptionFlags;
*/
//[2]参数类型的对应关系
/*
G_OPTION_ARG_NONE           gboolean
 
G_OPTION_ARG_STRING         gchar*
 
G_OPTION_ARG_INT            gint
 
G_OPTION_ARG_FILENAME       gchar*
 
G_OPTION_ARG_STRING_ARRAY   gchar**
 
G_OPTION_ARG_FILENAME_ARRAY gchar**
*/

 
 
 
 

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值