glib学习笔记3 命令行解析

转载请注明出处,或联系:fanyuanmail@126.com
传统的命令行解析,如果提供的参数很多,程序很不灵活,并且很容易出问题
while(getopt())
{
swtich() {
             case:
             case:
             case:
         }
}
比如实现下面这个参数,实现起来还是非常麻烦的。
[root@localhost glib_test]# ./glib_test -?
Usage:
  glib_test [OPTION...]

Help Options:
  -?, --help              Show help options
  --help-all              Show all help options
  --help-test group       display help output

Application Options:
  -n, --nodaemon          Don't run as daemon in background
  -d, --debug             Enable debug information output
  -s, --size=M            Input your size

glib提供了一套解析命令行的函数,程序实现如下,太晚了,明天再加注释。

#include <stdio.h>
#include <glib.h>
//#include <stdlib.h>
//#include <unistd.h>



static gboolean option_detach = FALSE;
static gboolean option_debug = FALSE;
static gint size = 8;
static GOptionEntry options[] = {
        { "nodaemon", 'n', 0,
                G_OPTION_ARG_NONE, &option_detach,
                "Don't run as daemon in background" },
        { "debug", 'd', 0,
                G_OPTION_ARG_NONE, &option_debug,
                "Enable debug information output" },
        { "size", 's', 0,
                G_OPTION_ARG_INT, &size,
                "Input your size","M" },
        { NULL },
};

int main(int argc, char *argv[])
{
        GOptionContext *context;
        GError *err = NULL;
        GOptionGroup *g_group;
        context = g_option_context_new(NULL);
        g_group = g_option_group_new("test group","test group display",
                "display help output", NULL, NULL);
        g_option_context_add_main_entries(context, options, NULL);
        g_option_context_add_group(context,g_group);
        if (g_option_context_parse(context, &argc, &argv, &err) == FALSE) {
                if (err != NULL) {
                        g_printerr("%s/n", err->message);
                        g_error_free(err);
                } else
                        g_printerr("An unknown error occurred/n");
                exit(1);
       }
        g_option_context_free(context);
        if (option_debug == FALSE) {
                g_printf("option debug disable/n");
        } else {
                g_printf("option debug enable/n");
        }

        if (option_detach == FALSE) {
                g_printf("option detach disable/n");
        } else {
                g_printf("option detach enable/n");
        }
        printf("size=%d/n",size);
        return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值