getopt.c 1.1 KB

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