All things are difficult before they are easy. 没有软件的裸机是一具僵尸,没有硬件的软件是一个幽灵。2012,专注于Linux和C语言,关注自动化、性能测试,关注开源社区和开源测试工具、方法,尝试测试团队管理!
C语言 对命令行参数的处理方法及实例
上一篇 /
下一篇 2010-12-12 16:15:29
/ 个人分类:C/C++
在C语言中,有时需要对在运行时加上命令行参数,那么如何对命令行传入的参数做解析和处理呢?getopt()
函数是一个标准库调用,可允许您使用直接的 while/switch 语句方便地逐个处理命令行参数和检测选项(带或不带附加的参数)。与其类似的getopt_long()
允许在几乎不进行额外工作的情况下处理更具描述性的长选项,这非常受开发人员的欢迎。实例1 getopt.c使用getopt():#include <stdio.h> #include <unistd.h>
int main(int argc,char *argv[]) { int ch; pterr=0; while((ch=getopt(argc,argv,"a:b::cde"))!=-1) { printf("optind:%d\n",optind); printf("optarg:%s\n",optarg); printf("ch:%c\n",ch); switch(ch) { case 'a': printf("option a:'%s'\n",optarg); break; case 'b': printf("option b:'%s'\n",optarg); break; case 'c': printf("option c\n"); break; case 'd': printf("option d\n"); break; case 'e': printf("option e\n"); break; default: printf("other option:%c\n",ch); } printf("optopt+%c\n",optopt); } } |
运行命令:./getopt -a 11 -b22 -e -foptind:3optarg:11ch:aoption a:'11'optopt+optind:4optarg:22ch:boption b:'22'optopt+optind:5optarg:(null)ch:eoption eoptopt+optind:6optarg:(null)ch:?other option:?optopt+f说明:getopt()函数的原型为getopt(int argc,char *const argv[],const char *optstring)。其中argc和argv一般就将main函数的那两个参数原样传入。optstring是一段自己规定的选项串,例如本例中的"a:b::cde",表示可以有,-a,-b,-c,-d,-e这几个参数。“:”表示必须该选项带有额外的参数,全域变量optarg会指向此额外参数,“::”标识该额外的参数可选(带的额外参数必须紧挨着该选项,有些Uinx可能不支持“::”)。全域变量optind指示下一个要读取的参数在argv中的位置。如果getopt()找不到符合的参数则会印出错信息,并将全域变量optopt设为“?”字符。如果不希望getopt()印出错信息,则只要将全域变量opterr设为0即可。实例2 getopt_long.c使用getopt_long():#include <stdio.h> #include <getopt.h>
int do_name, do_gf_name; char *l_opt_arg;
struct option longopts[] = { { "name", no_argument, NULL, 'n' }, { "gf_name", no_argument, NULL, 'g' }, { "love", required_argument, NULL, 'l' }, { 0, 0, 0, 0}, };
int main(int argc, char *argv[]) { int c; while((c = getopt_long(argc, argv, ":l:", longopts, NULL)) != -1){ switch (c){ case 'n': printf("My name is Jay.\n"); break; case 'g': printf("Her name is Afra.\n"); break; case 'l': l_opt_arg = optarg; printf("Our love is %s!\n", l_opt_arg); break; } } return 0; }
|
运行命令:./getopt_long --name --gf_name --love foreverMy name is Jay.Her name is Afra.Our love is forever!最详细的参考资料,见:http://blog.chinaunix.net/u/7040/showart_244389.html 写得非常的好,很详细的http://zhangxuming.blog.51cto.com/1762/126785
收藏
举报
TAG:
getopt
getopt_long
参数