- 如何实现命令行可选参数的输入(如:gcc -o test test.c),解析用户输入的命令
- 我们直到main函数有两个输入参数argc和argv,原型为 ```c int main(int argc, char **argv);
- argc记录了输入参数的个数
- argv是可理解为以一个字符串数组,里面保存了输入的参数
要注意解析命令里是否有&在最后,如果有&在命令最后,那么父进程就要wait子进程exit。
以./show_file [-s Size] [-f freetype_font_file] [-h HZK] <text_file>为例```cwhile ((iError = getopt(argc, argv, "ls:f:h:d:")) != -1) /* getopt函数对参数进行匹配,返回匹配到的参数 */{/* 选项 : ./show_file -l */switch(iError){case 'l':{bList = 1; /* 记录不带参数值的选项 */break;}case 's':{dwFontSize = strtoul(optarg, NULL, 0); /* optarg是getopt函数得到的具体参数值 */break;}case 'f':{strncpy(acFreetypeFile, optarg, 128);acFreetypeFile[127] = '\0';break;}case 'h':{strncpy(acHzkFile, optarg, 128);acHzkFile[127] = '\0';break;}case 'd':{strncpy(acDisplay, optarg, 128);acDisplay[127] = '\0';break;}default:{printf("Usage: %s [-s Size] [-d display] [-f font_file] [-h HZK] <text_file>\n", argv[0]);printf("Usage: %s -l\n", argv[0]);return -1;break;}}if (!bList && (optind >= argc)) /* 如果存在不带参数值的选项,但是optind超过了argc个数说明命令行输入错误了 */{printf("Usage: %s [-s Size] [-d display] [-f font_file] [-h HZK] <text_file>\n", argv[0]);printf("Usage: %s -l\n", argv[0]);return -1;}
可以看到采用getopt函数对输入参数进行解析
- getopt(argc, argv, “ls:f:h:d:”))
- “ls:f:h:d:” 表示需要解析的参数,字母后面带”:”表示参数需要带值,反之没有(如:l)



- getopt(argc, argv, “ls:f:h:d:”))
