base_getopt.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * This is a version of the public domain getopt implementation by
  3. * Henry Spencer originally posted to net.sources.
  4. *
  5. * This file is in the public domain.
  6. */
  7. #include <stdio.h>
  8. #include <string.h>
  9. #define getopt fz_getopt
  10. #define optarg fz_optarg
  11. #define optind fz_optind
  12. char *optarg; /* Global argument pointer. */
  13. int optind = 0; /* Global argv index. */
  14. static char *scan = NULL; /* Private scan pointer. */
  15. int
  16. getopt(int argc, char *argv[], char *optstring)
  17. {
  18. char c;
  19. char *place;
  20. optarg = NULL;
  21. if (!scan || *scan == '\0') {
  22. if (optind == 0)
  23. optind++;
  24. if (optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0')
  25. return EOF;
  26. if (argv[optind][1] == '-' && argv[optind][2] == '\0') {
  27. optind++;
  28. return EOF;
  29. }
  30. scan = argv[optind]+1;
  31. optind++;
  32. }
  33. c = *scan++;
  34. place = strchr(optstring, c);
  35. if (!place || c == ':') {
  36. fprintf(stderr, "%s: unknown option -%c\n", argv[0], c);
  37. return '?';
  38. }
  39. place++;
  40. if (*place == ':') {
  41. if (*scan != '\0') {
  42. optarg = scan;
  43. scan = NULL;
  44. } else if( optind < argc ) {
  45. optarg = argv[optind];
  46. optind++;
  47. } else {
  48. fprintf(stderr, "%s: option requires argument -%c\n", argv[0], c);
  49. return ':';
  50. }
  51. }
  52. return c;
  53. }