Based on the original Rocket Workbench on SourceForge in CVS at: https://sourceforge.net/projects/rocketworkbench
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.5 KiB

  1. /* file getopt.c */
  2. /* Author: Peter Wilson */
  3. /* Catholic University and NIST */
  4. /* pwilson@cme.nist.gov */
  5. /* */
  6. /* getopt() from Don Libes "Obfuscated C" */
  7. #include <stdio.h>
  8. #include <string.h>
  9. /* getopt() -- parse command line arguments */
  10. /* Original Author: AT&T */
  11. /* This version from Don Libes "Obfuscated C and Other Mysteries" */
  12. /* John Wiley & Sons, 1993. Chapter 6 */
  13. #define ERR(s, c) if (opterr) {\
  14. char errbuf[3];\
  15. errbuf[0] = c; errbuf[1] = '\n'; errbuf[2] = '\0'; \
  16. fprintf(stderr, "%s", argv[0]);\
  17. fprintf(stderr, "%s", s);\
  18. fprintf(stderr, "%s", errbuf); }
  19. int opterr = 1; /* getopt prints errors if this is one */
  20. int optind = 1; /* token pointer */
  21. int optopt; /* option character passed back to user */
  22. char *optarg; /* flag argument (or value) */
  23. /* return option option character, EOF if no more or ? if problem */
  24. int getopt(int argc, char **argv, char *opts) /* opts: option string */
  25. {
  26. static int sp = 1; /* character index in current token */
  27. register char *cp; /* pointer into current token */
  28. if (sp == 1) {
  29. /* check for more flag-like tokens */
  30. if(optind >= argc ||
  31. argv[optind][0] != '-' || argv[optind][1] == '\0')
  32. return(EOF);
  33. else if(strcmp(argv[optind], "--") == 0) {
  34. optind++;
  35. return(EOF);
  36. }
  37. }
  38. optopt = argv[optind][sp];
  39. if(optopt == ':' || ( cp = strchr(opts, optopt)) == 0) {
  40. ERR(": illegal option -- ", optopt);
  41. /* if no chars left in this token, move to next token */
  42. if(argv[optind][++sp] == '\0') {
  43. optind++;
  44. sp = 1;
  45. }
  46. return('?');
  47. }
  48. if(*++cp == ':') {/* if a value is expected, get it */
  49. if(argv[optind][sp+1] != '\0')
  50. /* flag value is rest of current token */
  51. optarg = &argv[optind++][sp+1];
  52. else if (++optind >= argc) {
  53. ERR(": option requires an argument -- ", optopt);
  54. sp = 1;
  55. return('?');
  56. } else
  57. /* flag value is next token */
  58. optarg = argv[optind++];
  59. sp = 1;
  60. } else {
  61. /* set up to look at next char in token, next time */
  62. if(argv[optind][++sp] == '\0') {
  63. /* no m ore in current token, set up next token */
  64. sp = 1;
  65. optind++;
  66. }
  67. optarg = 0;
  68. }
  69. return(optopt); /* return current flag character found */
  70. }