[c language] getopt 其参数optind 及其main(int argc, char **argv) 参数解释

时间:2023-12-20 10:43:56

getopt被用来解析命令行选项参数。
#include <unistd.h>

extern char *optarg; //选项的参数指针
extern int optind, //下一次调用getopt的时,从optind存储的位置处重新开始检查选项。
extern int opterr, //当opterr=0时,getopt不向stderr输出错误信息。
extern int optopt; //当命令行选项字符不包括在optstring中或者选项缺少必要的参数时,该选项存储在optopt 中,getopt返回'?’

 #include <stdio.h>
#include <unistd.h>
#include <stdlib.h> #ifdef RDP2
#define VNCOPT "V:Q"
#else
#define VNCOPT "V:"
#endif int main(int argc, char **argv)
{
int ch, i;
opterr = ; while ((ch = getopt(argc,argv, VNCOPT ":a:bcde::f"))!=-)
{
printf("optind:%d,opterr:%d\n", optind, opterr);
switch(ch)
{
case 'V':
printf("option V:'%s'\n",optarg);
break;
case 'a':
i = strtol(optarg, NULL, );
printf("i = %x\n", i);
printf("option a:'%s'\n",optarg);
break;
case 'b':
printf("option b :b\n");
break;
case 'e':
printf("option e:'%s'\n",optarg);
break;
default:
printf("other option :%c\n",ch);
}
}
for(int i = ; i < argc; i++)
printf("argv[%d] = [%s]\n", i, argv[i]);
printf("argc = [%d]\n", argc);
printf("optopt +%c\n",optopt); return ;
}

执行结果:

$ ./getopt -a  -bcd -e
i =
option a:''
optind:,opterr:
option b :b
optind:,opterr:
other option :c
optind:,opterr:
other option :d
optind:,opterr:
option e:''
optind:,opterr:
argv[] = [./getopt]
argv[] = [-a]
argv[] = []
argv[] = [-bcd]
argv[] = [-e]
argv[] = []
argc = []
optopt +e
optind =

argv 数组存储命令行字符串(包含./getopt执行程序)

argc 命令行字符串个数(./getopt -a 123 -bcd -e 456) 6个

optind 下一次调用getopt的时,从optind存储的位置处重新开始检查选项。从0开始计算

(对应下面位置)

./getopt -a 123 -bcd -e 456

0       1   2     3     4   5   6