getopt_long.c 1.8 KB

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