2
0

getopt.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include "test_helpers.h"
  4. #define RUN(...) \
  5. do { \
  6. optind = 1; \
  7. optarg = NULL; \
  8. opterr = 1; \
  9. optopt = -1; \
  10. char *args_arr[] = { __VA_ARGS__ }; \
  11. printf("result: %d\n", runner(sizeof(args_arr) / sizeof(args_arr[0]), args_arr)); \
  12. } while (0)
  13. int runner(int argc, char *argv[]) {
  14. int c;
  15. int bflg = 0, aflg = 0, errflg = 0;
  16. char *ifile = "";
  17. char *ofile = "";
  18. while((c = getopt(argc, argv, ":abf:o:")) != -1) {
  19. switch(c) {
  20. case 'a':
  21. if(bflg)
  22. errflg++;
  23. else
  24. aflg++;
  25. break;
  26. case 'b':
  27. if(aflg)
  28. errflg++;
  29. else
  30. bflg++;
  31. break;
  32. case 'f':
  33. ifile = optarg;
  34. break;
  35. case 'o':
  36. ofile = optarg;
  37. break;
  38. case ':':
  39. printf("Option -%c requires an operand\n", optopt);
  40. errflg++;
  41. break;
  42. case '?':
  43. printf("Unrecognized option: -%c\n", optopt);
  44. errflg++;
  45. }
  46. }
  47. printf("bflg: %d\n", bflg);
  48. printf("aflg: %d\n", aflg);
  49. printf("errflg: %d\n", errflg);
  50. printf("ifile: %s\n", ifile);
  51. printf("ofile: %s\n", ofile);
  52. if(errflg) {
  53. printf("Usage: info goes here\n");
  54. return 2;
  55. }
  56. return 0;
  57. }
  58. int main(int argc, const char *argv[]) {
  59. RUN("test", "-ao", "arg", "path", "path");
  60. RUN("test", "-a", "-o", "arg", "path", "path");
  61. RUN("test", "-o", "arg", "-a", "path", "path");
  62. RUN("test", "-a", "-o", "arg", "--", "path", "path");
  63. RUN("test", "-a", "-oarg", "path", "path");
  64. RUN("test", "-aoarg", "path", "path");
  65. RUN("test");
  66. }