#include <stdio.h> #include <stdlib.h> #include <getopt.h>
/********************************************************* * struct option { * const char *name; //option name * int has_arg; //describe option parameters * int *flag; // * int val; // * } * about has_arg: * no_argument 0 * required_argument 1 * optional_argument 2 ********************************************************* * about return value * 0: return 0 if flag isn't NULL * 'x': option character * '?': invalid option * ':': lack of option parameter * -1: option parse over ********************************************************* */
int g_help = 0; int g_ver = 0;
const char *soptions = "hvp:"; const struct option loptions1[] = { {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'v'}, {"path", required_argument, NULL, 'p'}, {NULL, 0, NULL, 0} }; const struct option loptions2[] = { {"help", no_argument, &g_help, 1}, {"version", no_argument, &g_ver, 1}, {"path", optional_argument, NULL, 'p'}, {NULL, 0, NULL, 0} };
int parse1(int argc, char **argv) { char *path = NULL; int ret = 0;
while (-1 != (ret = getopt_long(argc, argv, soptions, loptions1, NULL))) { switch (ret) { case 'h': printf("param: help\n"); break; case 'v': printf("param: version\n"); break; case 'p': path = optarg; printf("param: path=%s\n", path); break; case ':': printf("param: lack long options\n"); break; case '?': printf("param: unspecified param\n"); break; } }
return 0; }
int parse2(int argc, char **argv) { char *path = NULL; int ret = 0;
while (-1 != (ret = getopt_long(argc, argv, soptions, loptions2, NULL))) { switch (ret) { case 0: printf("g_help = %d, g_ver = %d\n", g_help, g_ver); break; case 'p': path = optarg; printf("param: path=%s\n", path); break; case ':': printf("param: lack long options\n"); break; case '?': printf("param: unspecified param\n"); break; } }
return 0; }
int main(int argc, char **argv) { parse1(argc, argv); parse2(argc, argv);
return 0; }
|