免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1141 | 回复: 0
打印 上一主题 下一主题

glib学习笔记3 命令行解析 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-12-23 00:47 |只看该作者 |倒序浏览
转载请注明出处,或联系: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;
}
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/58855/showart_1735932.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP