一、optargs
optargs是一个可选参数列表,列表中的每一个元素都是一个字符串。它是在getopt函数中定义并声明的。
#include<stdio.h> #include<stdlib.h> #include<getopt.h> int main(int argc, char *argv[]) { int flag_a = 0; int option_index = 0; struct option long_options[] = { {"all", no_argument, 0, 'a'}, {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {"output", required_argument, 0, 'o'}, {"verbose", no_argument, 0, 'v'}, {0, 0, 0, 0} }; int opt = 0; while ((opt = getopt_long(argc, argv, "aho:v", long_options, &option_index)) != -1) { switch(opt) { case 'a': flag_a = 1; break; case 'h': printf("help\n"); break; case 'o': printf("the output file name is %s\n", optarg); break; case 'v': printf("version 1.0\n"); break; default: printf("Unknown option: %c\n", opt); break; } } if (flag_a) printf("option -a is enabled\n"); return 0; }
在这个例子里,当选项o被使用时,输出文件名将由optarg返回。
二、optarg赋值
optarg是在getopt中声明的,它指向当前选项参数(如果有的话)。
#include<stdio.h> #include<stdlib.h> #include<unistd.h> int main(int argc, char *argv[]) { int ch; char *opt_arg = NULL; while ((ch = getopt(argc, argv, "n:")) != -1) { switch (ch) { case 'n': opt_arg = optarg; printf("opt_arg=%s\n", opt_arg); } } return 0; }
在这个例子里,当选项n被使用时,optarg返回参数n的值。
三、optargin
optargin表示argv中当前选项参数的位置。
#include<stdio.h> #include<stdlib.h> #include<unistd.h> int main(int argc, char *argv[]) { int ch; char *opt_arg = NULL; while ((ch = getopt(argc, argv, "n:")) != -1) { switch (ch) { case 'n': opt_arg = optarg; printf("optarg=%s, optind=%d\n",opt_arg, optind); } } return 0; }
在这个例子里,当选项n被使用时,optind返回当前参数在argv中的位置。
四、optarg shell
在shell中,optarg是由“getopts”命令处理的。getopts是一个用来解析命令行选项的shell内建命令。
#!/bin/sh while getopts ab:ch OPT do case $OPT in "a" ) FLG_A="TRUE" ;; "b" ) FLG_B="TRUE" ; VALUE_B="$OPTARG" ;; "c" ) FLG_C="TRUE" ;; "h" ) usage ;; * ) usage ;; esac done echo "FLG_A = $FLG_A" echo "FLG_B = $FLG_B" echo "VALUE_B = $VALUE_B" echo "FLG_C = $FLG_C"
在这个例子里,当选项b被使用时,optarg返回参数b的值。
五、optarg参数赋值
在C中,可以为选项参数赋值,在选项字母的后面紧跟着一个冒号”:”, 后面的文本就是一个值,是选项的取值部分。
#include<stdio.h> #include<stdlib.h> #include<unistd.h> int main(int argc, char *argv[]) { int ch; char *opt_arg = NULL; while ((ch = getopt(argc, argv, "n:")) != -1) { switch (ch) { case 'n': opt_arg = optarg; printf("opt_arg=%s\n", opt_arg); } } return 0; }
在这个例子里,当选项n被使用时,optarg返回选项参数的值。
原创文章,作者:XXLOI,如若转载,请注明出处:https://www.506064.com/n/371003.html