getopt.c 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #include <stdio.h>
  2. #define EPR fprintf(stderr,
  3. #define ERR(str, chr) if(opterr){EPR "%s%c\n", str, chr);}
  4. int opterr = 1;
  5. int optind = 1;
  6. int optopt;
  7. char *optarg;
  8. char *strchr();
  9. int
  10. getopt (int argc, char *const argv[], const char *opts)
  11. {
  12. static int sp = 1;
  13. int c;
  14. char *cp;
  15. if (sp == 1)
  16. if (optind >= argc ||
  17. argv[optind][0] != '-' || argv[optind][1] == '\0')
  18. return -1;
  19. else if (strcmp(argv[optind], "--") == 0) {
  20. optind++;
  21. return -1;
  22. }
  23. optopt = c = argv[optind][sp];
  24. if (c == ':' || (cp=strchr(opts, c)) == 0) {
  25. ERR (": illegal option -- ", c);
  26. if (argv[optind][++sp] == '\0') {
  27. optind++;
  28. sp = 1;
  29. }
  30. return '?';
  31. }
  32. if (*++cp == ':') {
  33. if (argv[optind][sp+1] != '\0')
  34. optarg = &argv[optind++][sp+1];
  35. else if (++optind >= argc) {
  36. ERR (": option requires an argument -- ", c);
  37. sp = 1;
  38. return '?';
  39. } else
  40. optarg = argv[optind++];
  41. sp = 1;
  42. } else {
  43. if (argv[optind][++sp] == '\0') {
  44. sp = 1;
  45. optind++;
  46. }
  47. optarg = 0;
  48. }
  49. return c;
  50. }