标签:blog http io ar 使用 for sp div on
from:http://blog.csdn.net/mr_jj_lian/article/details/6835137
命令行参数解析函数 —— getopt()
#include <unistd.h> int getopt(int argc, char * const argv[], const char *optstring); extern char *optarg; extern int optind, opterr, optopt; |
argc
)、指向这些参数的数组 (argv
) 和选项字串 (optstring
) 后,getopt()
将返回第一个选项,并设置一些全局变量。使用相同的参数再次调用该函数时,它将返回下一个选项,并设置相应的全局变量。如果不再有可识别的选项,将返回 -1
,此任务就完成了。getopt()
所设置的全局变量包括:char *optarg
——当前选项参数字串(如果有)。int optind
——argv的当前索引值。当getopt()在while循环中使用时,循环结束后,剩下的字串视为操作数,在argv[optind]至argv[argc-1]中可以找到。int optopt
——当发现无效选项字符之时,getopt()函数或返回‘?‘字符,或返回‘:‘字符,并且optopt包含了所发现的无效选项字符。#include <stdio.h> #include <unistd.h> 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 <stdio.h> #include <unistd.h> 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 <stdio.h> #include <unistd.h> 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; } |
$ ./opt_parse_demo -a
无效的选项字符 ‘ a ‘!
$ ./opt_parse_demo -l
缺少选项参数!
标签:blog http io ar 使用 for sp div on
原文地址:http://www.cnblogs.com/chrispauls/p/4039697.html