getopt.c 1.8 KB

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