• 如何实现命令行可选参数的输入(如:gcc -o test test.c),解析用户输入的命令
    • 我们直到main函数有两个输入参数argc和argv,原型为 ```c int main(int argc, char **argv);
    • argc记录了输入参数的个数
    • argv是可理解为以一个字符串数组,里面保存了输入的参数
    • 要注意解析命令里是否有&在最后,如果有&在命令最后,那么父进程就要wait子进程exit。

      1. 以./show_file [-s Size] [-f freetype_font_file] [-h HZK] <text_file>为例
      2. ```c
      3. while ((iError = getopt(argc, argv, "ls:f:h:d:")) != -1) /* getopt函数对参数进行匹配,返回匹配到的参数 */
      4. {
      5. /* 选项 : ./show_file -l */
      6. switch(iError)
      7. {
      8. case 'l':
      9. {
      10. bList = 1; /* 记录不带参数值的选项 */
      11. break;
      12. }
      13. case 's':
      14. {
      15. dwFontSize = strtoul(optarg, NULL, 0); /* optarg是getopt函数得到的具体参数值 */
      16. break;
      17. }
      18. case 'f':
      19. {
      20. strncpy(acFreetypeFile, optarg, 128);
      21. acFreetypeFile[127] = '\0';
      22. break;
      23. }
      24. case 'h':
      25. {
      26. strncpy(acHzkFile, optarg, 128);
      27. acHzkFile[127] = '\0';
      28. break;
      29. }
      30. case 'd':
      31. {
      32. strncpy(acDisplay, optarg, 128);
      33. acDisplay[127] = '\0';
      34. break;
      35. }
      36. default:
      37. {
      38. printf("Usage: %s [-s Size] [-d display] [-f font_file] [-h HZK] <text_file>\n", argv[0]);
      39. printf("Usage: %s -l\n", argv[0]);
      40. return -1;
      41. break;
      42. }
      43. }
      44. if (!bList && (optind >= argc)) /* 如果存在不带参数值的选项,但是optind超过了argc个数说明命令行输入错误了 */
      45. {
      46. printf("Usage: %s [-s Size] [-d display] [-f font_file] [-h HZK] <text_file>\n", argv[0]);
      47. printf("Usage: %s -l\n", argv[0]);
      48. return -1;
      49. }
    • 可以看到采用getopt函数对输入参数进行解析

      • getopt(argc, argv, “ls:f:h:d:”))
        • “ls:f:h:d:” 表示需要解析的参数,字母后面带”:”表示参数需要带值,反之没有(如:l)
      • image.png
      • image.png
      • image.png