2
0

getopt_long.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include <getopt.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. runner(sizeof(args_arr) / sizeof(char*), args_arr); \
  12. } while (0)
  13. void runner(int argc, char *argv[]) {
  14. printf("--- Running:");
  15. for (int i = 0; i < argc; i += 1) {
  16. printf(" %s", argv[i]);
  17. }
  18. puts("");
  19. static int flag = 0;
  20. static struct option long_options[] = {
  21. {"test0", no_argument, NULL, 1},
  22. {"test1", no_argument, &flag, 2},
  23. {"test2", optional_argument, NULL, 3},
  24. {"test3", required_argument, NULL, 4},
  25. {NULL, 0, NULL, 5},
  26. };
  27. int option_index = 0;
  28. char c;
  29. while((c = getopt_long(argc, argv, ":a", long_options, &option_index)) != -1) {
  30. switch(c) {
  31. case 'a':
  32. printf("Option -a with value %s\n", optarg);
  33. break;
  34. case ':':
  35. printf("unrecognized argument: -%c\n", optopt);
  36. break;
  37. case '?':
  38. printf("error: -%c\n", optopt);
  39. break;
  40. default:
  41. printf("getopt_long returned %d, ", c);
  42. if (flag) {
  43. printf("set flag to %d, ", flag);
  44. flag = 0;
  45. }
  46. printf("argument %s=%s\n", long_options[option_index].name, optarg);
  47. break;
  48. }
  49. }
  50. }
  51. int main(int argc, const char *argv[]) {
  52. RUN("test", "--test0", "-a");
  53. RUN("test", "--test1", "-a");
  54. RUN("test", "--test2", "-a");
  55. RUN("test", "--test2=arg", "-a");
  56. RUN("test", "--test3", "-a");
  57. RUN("test", "--test3=arg", "-a");
  58. RUN("test", "--test3", "arg", "-a");
  59. }