一、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/zh-hant/n/371003.html