my_getopt.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include <getopt.h>
  2. #include <string.h>
  3. #include <kopano/my_getopt.h>
  4. namespace KC {
  5. int my_getopt_long_permissive(int argc, char **argv, const char *shortopts,
  6. const struct option *longopts, int *longind)
  7. {
  8. int opterr_save = opterr, saved_optind = optind;
  9. opterr = 0;
  10. int c = getopt_long(argc, argv, shortopts, longopts, longind);
  11. if (c == '?') {
  12. // Move this parameter to the end of the list if it a long option
  13. if (argv[optind - 1][0] == '-' && argv[optind - 1][1] == '-' && argv[optind - 1][2] != '\0') {
  14. int i = optind - 1;
  15. /*
  16. * Continue parsing at the next argument before moving the unknown
  17. * option to the end, otherwise a potentially endless loop could
  18. * ensue.
  19. */
  20. c = getopt_long(argc, argv, shortopts, longopts, longind);
  21. char *tmp = argv[i];
  22. int move_count = (argc - i) - i;
  23. if (move_count > 0)
  24. memmove(&argv[i], &argv[i + 1], move_count * sizeof(char *));
  25. argv[i] = tmp;
  26. --optind;
  27. --saved_optind;
  28. }
  29. }
  30. opterr = opterr_save;
  31. // Show error
  32. if (c == '?') {
  33. optind = saved_optind;
  34. getopt_long(argc, argv, shortopts, longopts, longind);
  35. }
  36. return c;
  37. }
  38. } /* namespace */