赞
踩
在写一些可执行程序时,常常会传递一些参数。getopt函数就是专门用来处理选项参数的。
- #include <unistd.h>
-
- extern char *optarg;
- extern int optind, opterr, optopt;
-
- int getopt(int argc, char * const argv[], const char *optstring);
argc和argv就是命令行传入的参数。
optstring是支持的选项列表。具体规则如下:
optarg、optind、opterr、optopt:
当getopt解析到一个并不在optstring中的选项时,或者一个必须跟参数的选项后面没有参数时,其返回值就是'?'(0x3f)。optopt指向当前的选项。
了解了上面的接口和相关参数,就可以通过循环调用getopt来解析一长串的参数。
- #include <unistd.h>
- #include <stdio.h>
- #include <string.h>
-
- extern int optind, opterr, optopt;
- extern char* optarg;
-
-
- void show_help(char* exe)
- {
- printf("Usage: %s -<w/r> [info]\r\n");
- }
-
- void main(int argc, char* argv[])
- {
- int ch;
-
- printf("optind = %d.\r\n", optind);
- while ((ch = getopt(argc, argv, "w:rh::")) != -1) {
- printf("optind = %d.\r\n", optind);
- switch (ch) {
- case 'w':
- printf("get w. optarg = %s. optind = %d\r\n", optarg, optind);
- break;
- case 'r':
- printf("get r. optarg = %s\r\n", optarg);
- break;
- case 'h':
- printf("get h.\r\n");
- break;
- default:
- printf("default ch = %d. optopt = %d\r\n", ch, optopt);
- break;
- }
- }
-
-
- printf("end.\r\n");
-
- }
运用好optind、optarg变量,再加上一些具体应用所需的策略,即可完成对命令行参数的解析。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。