转自:http://blog.csdn.net/yunhappy/archive/2010/03/08/5356945.aspx
以前写程序时 遇到需要接收参数时,总是自己printf,自己去parse。总是感觉很机械,繁琐,不过主要也都是服务端程序,一般不需要提供给其他人用。
不过,哈哈 最近发现了一个好东东,GOptionEntry :http://library.gnome.org/devel/glib/stable/glib-Commandline-option-parser.html
一个小例子:
- static gint repeats = 2;
- static gint max_size = 8;
- static gboolean verbose = FALSE;
- static gboolean beep = FALSE;
- static gboolean op_rand = FALSE;
- static gchar arg_data[32] = { "arg data" };
- static GOptionEntry entries[] =
- {
- {"long name" , 's' /*short-name*/ , 0 /*flags*/ , G_OPTION_ARG_STRING /*arg*/ ,
- arg_data,
- "description" , "arg_description" },
- {"repeats" , 'r' , 0, G_OPTION_ARG_INT,
- &repeats, "Average over N repetitions" , "N" },
- {"max-size" , 'm' , 0, G_OPTION_ARG_INT,
- &max_size, "Test up to 2^M items" , "M" },
- {"verbose" , 'v' , 0, G_OPTION_ARG_NONE,
- &verbose, "Be verbose" , NULL},
- {"beep" , 'b' , 0, G_OPTION_ARG_NONE,
- &beep, "Beep when done" , NULL},
- {"rand" , 0, 0, G_OPTION_ARG_NONE,
- &op_rand, "Randomize the data" , NULL},
- {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);
- g_option_context_set_summary(context, "my-add-summary" );
- // g_option_context_add_group(context, gtk_get_option_group(TRUE));
- if (!g_option_context_parse(context, &argc, &argv, &error)) {
- g_print("option parsing failed: %s/n" , error->message);
- exit (1);
- }
- g_option_context_free(context);
- g_print("Now value is: repeats=%d, max_size=%d, /n" ,
- repeats, max_size);
- return 0;
- }
丛上面的例子可以看出,程序的Commandline parse主要工作就变成了
GOptionEntry 的定义:
- typedef struct {
- const gchar *long_name; // 参数的完整名
- gchar short_name; // 简写名
- gint flags; // 参数选项标准 不关心直接赋0
- GOptionArg arg; // 参数类型,int,string...
- gpointer arg_data; // 默认参数值
- const gchar *description; // 参数意义说明
- const gchar *arg_description; // 参数占位符说明
- } GOptionEntry;
同时还需要注意 不要引起内存泄露:
Please note that parsed arguments need to be freed separately (see GOptionEntry ).
运行结果输出如下:
- [yunm@yunmiao src]$ ./test --help
- Usage:
- test [OPTION...] - test tree model performance
- my-add-summary
- Help Options:
- -h, --help Show help options
- Application Options:
- -s, --long name=arg_description description
- -r, --repeats=N Average over N repetitions
- -m, --max-size=M Test up to 2^M items
- -v, --verbose Be verbose
- -b, --beep Beep when done
- --rand Randomize the data
- [yunm@yunmiao src]$ ./test -r 10 -m 2
- Now value is: repeats=10, max_size=2,
- [yunm@yunmiao src]$ ./test
- Now value is: repeats=2, max_size=8,
- [yunm@yunmiao src]$ ./test -r 111111111111111111111
- option parsing failed: Integer value '111111111111111111111' for -r out of range
这样一来,又大大加进了我们程序的标准化进程。 ^_^