分类: LINUX
2011-08-31 13:26:48
#include int getopt(int argc, char * const argv[], const char *optstring); extern char *optarg; extern int optind, opterr, optopt; |
#include #include int main (int argc, char **argv) { int oc; /*选项字符 */ char *b_opt_arg; /*选项参数字串 */ while((oc = getopt(argc, argv, "ngl:")) != -1) { switch(oc) { case 'n': printf("My name is Lyong.\n"); break; case 'g': printf("Her name is Xxiong.\n"); break; case 'l': b_opt_arg = optarg; printf("Our love is %s\n", optarg); break; } } return 0; } |
$ ./opt_parse_demo -n My name is Lyong. $ ./opt_parse_demo -g Her name is Xxiong. $ ./opt_parse_demo -l forever Our love is forever $ ./opt_parse_demo -ngl forever My name is Lyong. Her name is Xxiong. Our love is forever |
#include #include int main (int argc, char **argv) { int oc; /*选项字符 */ char *b_opt_arg; /*选项参数字串 */ while((oc = getopt(argc, argv, "ngl:")) != -1) { switch(oc) { case 'n': printf("My name is Lyong.\n"); break; case 'g': printf("Her name is Xxiong.\n"); break; case 'l': b_opt_arg = optarg; printf("Our love is %s\n", optarg); break; case '?': printf("arguments error!\n"); break; } } return 0; } |
$ ./opt_parse_demo -l ./opt_parse_demo: option requires an argument -- l arguments error! |
#include #include int main (int argc, char **argv) { int oc; /*选项字符 */ char ec; /*无效的选项字符*/ char *b_opt_arg; /*选项参数字串 */ while((oc = getopt(argc, argv, ":ngl:")) != -1) { switch(oc) { case 'n': printf("My name is Lyong.\n"); break; case 'g': printf("Her name is Xxiong.\n"); break; case 'l': b_opt_arg = optarg; printf("Our love is %s\n", optarg); break; case '?': ec = (char)optopt; printf("无效的选项字符 \' %c \'!\n", ec); break; case ':': printf("缺少选项参数!\n"); break; } } return 0; } |