getopt_long.c 1.7 KB

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