glib学习笔记3 命令行解析

来源:百度文库 编辑:神马文学网 时间:2024/04/28 18:50:34
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
#include
//#include
//#include



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;
}


发表于: 2008-12-23,修改于: 2008-12-23 00:47,已浏览32次,有评论0条 推荐 投诉