getopt.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #define _BSD_SOURCE
  2. #include <unistd.h>
  3. #include <wchar.h>
  4. #include <string.h>
  5. #include <limits.h>
  6. #include <stdlib.h>
  7. #include "locale_impl.h"
  8. #include "stdio_impl.h"
  9. char *optarg;
  10. int optind=1, opterr=1, optopt, __optpos, __optreset=0;
  11. #define optpos __optpos
  12. weak_alias(__optreset, optreset);
  13. void __getopt_msg(const char *a, const char *b, const char *c, size_t l)
  14. {
  15. FILE *f = stderr;
  16. b = __lctrans_cur(b);
  17. FLOCK(f);
  18. fputs(a, f)>=0
  19. && fwrite(b, strlen(b), 1, f)
  20. && fwrite(c, 1, l, f)==l
  21. && putc('\n', f);
  22. FUNLOCK(f);
  23. }
  24. int getopt(int argc, char * const argv[], const char *optstring)
  25. {
  26. int i;
  27. wchar_t c, d;
  28. int k, l;
  29. char *optchar;
  30. if (!optind || __optreset) {
  31. __optreset = 0;
  32. __optpos = 0;
  33. optind = 1;
  34. }
  35. if (optind >= argc || !argv[optind])
  36. return -1;
  37. if (argv[optind][0] != '-') {
  38. if (optstring[0] == '-') {
  39. optarg = argv[optind++];
  40. return 1;
  41. }
  42. return -1;
  43. }
  44. if (!argv[optind][1])
  45. return -1;
  46. if (argv[optind][1] == '-' && !argv[optind][2])
  47. return optind++, -1;
  48. if (!optpos) optpos++;
  49. if ((k = mbtowc(&c, argv[optind]+optpos, MB_LEN_MAX)) < 0) {
  50. k = 1;
  51. c = 0xfffd; /* replacement char */
  52. }
  53. optchar = argv[optind]+optpos;
  54. optpos += k;
  55. if (!argv[optind][optpos]) {
  56. optind++;
  57. optpos = 0;
  58. }
  59. if (optstring[0] == '-' || optstring[0] == '+')
  60. optstring++;
  61. i = 0;
  62. d = 0;
  63. do {
  64. l = mbtowc(&d, optstring+i, MB_LEN_MAX);
  65. if (l>0) i+=l; else i++;
  66. } while (l && d != c);
  67. if (d != c || c == ':') {
  68. optopt = c;
  69. if (optstring[0] != ':' && opterr)
  70. __getopt_msg(argv[0], ": unrecognized option: ", optchar, k);
  71. return '?';
  72. }
  73. if (optstring[i] == ':') {
  74. optarg = 0;
  75. if (optstring[i+1] != ':' || optpos) {
  76. optarg = argv[optind++];
  77. if (optpos) optarg += optpos;
  78. optpos = 0;
  79. }
  80. if (optind > argc) {
  81. optopt = c;
  82. if (optstring[0] == ':') return ':';
  83. if (opterr) __getopt_msg(argv[0],
  84. ": option requires an argument: ",
  85. optchar, k);
  86. return '?';
  87. }
  88. }
  89. return c;
  90. }
  91. weak_alias(getopt, __posix_getopt);