C语言-解析命令行参数

时间:2022-12-06 14:28:48


#include <stdio.h>
#include<unistd.h>

/*
函数说明 :
int getopt(int argc,char * const argv[ ],const char * optstring);)
用来分析命令行参数。参数argc和argv分别代表参数个数和内容,跟main()函数的命令行参数是一样的。
参数 optstring为选项字符串, 告知 getopt()可以处理哪个选项以及哪个选项需要参数,如果选项字符串里的字母后接着冒号“:”,
则表示还有相关的参数,全域变量optarg 即会指向此额外参数。如果在处理期间遇到了不符合optstring指定的其他选项getopt()将显示一个错误消息,
并将全域变量optarg设为 “?”字符,如果不希望getopt()打印出错信息,则只要将全域变量opterr设为0即可。
*/
int main(int argc,char *argv[])
{
int opt;
opterr =0 ;//不输出错误

while ((opt = getopt (argc, argv, "A:B:C:")) != EOF)
switch (opt)
{
case 'A': printf("\033[40;31m *parameter a is:%s* \033[0m \n",optarg);
break;
case 'B': printf("parameter B is:%s\n",optarg);
break;
case 'C': printf("parameter C is:%s\n",optarg);
break;
default:
printf("other option is wrong\n");
}
return 0;
}

C语言-解析命令行参数