getopt.c 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <stdio.h>
  4. #define ERR(str, chr) if(opterr){fprintf(stderr, "%s%s%c\n", argv[0], str, chr);}
  5. int opterr = 1;
  6. int optind = 1;
  7. int optopt;
  8. char *optarg;
  9. int
  10. getopt (int argc, char **argv, char *opts)
  11. {
  12. static int sp = 1;
  13. register c;
  14. register char *cp;
  15. if (sp == 1)
  16. if (optind >= argc ||
  17. argv[optind][0] != '-' || argv[optind][1] == '\0')
  18. return EOF;
  19. else if (strcmp(argv[optind], "--") == NULL) {
  20. optind++;
  21. return EOF;
  22. }
  23. optopt = c = argv[optind][sp];
  24. if (c == ':' || (cp=strchr(opts, c)) == NULL) {
  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 = NULL;
  48. }
  49. return c;
  50. }