/bin/pax/getoldopt.c

https://bitbucket.org/freebsd/freebsd-head/ · C · 73 lines · 51 code · 12 blank · 10 comment · 16 complexity · 5fcd6f0dd0d95d7d505c225f42c51ac4 MD5 · raw file

  1. /* $OpenBSD: getoldopt.c,v 1.9 2009/10/27 23:59:22 deraadt Exp $ */
  2. /* $NetBSD: getoldopt.c,v 1.3 1995/03/21 09:07:28 cgd Exp $ */
  3. /*-
  4. * Plug-compatible replacement for getopt() for parsing tar-like
  5. * arguments. If the first argument begins with "-", it uses getopt;
  6. * otherwise, it uses the old rules used by tar, dump, and ps.
  7. *
  8. * Written 25 August 1985 by John Gilmore (ihnp4!hoptoad!gnu) and placed
  9. * in the Public Domain for your edification and enjoyment.
  10. */
  11. #include <sys/cdefs.h>
  12. __FBSDID("$FreeBSD$");
  13. #include <sys/types.h>
  14. #include <sys/stat.h>
  15. #include <stdio.h>
  16. #include <string.h>
  17. #include <unistd.h>
  18. #include "pax.h"
  19. #include "extern.h"
  20. int
  21. getoldopt(int argc, char **argv, const char *optstring)
  22. {
  23. static char *key; /* Points to next keyletter */
  24. static char use_getopt; /* !=0 if argv[1][0] was '-' */
  25. char c;
  26. char *place;
  27. optarg = NULL;
  28. if (key == NULL) { /* First time */
  29. if (argc < 2)
  30. return (-1);
  31. key = argv[1];
  32. if (*key == '-')
  33. use_getopt++;
  34. else
  35. optind = 2;
  36. }
  37. if (use_getopt)
  38. return (getopt(argc, argv, optstring));
  39. c = *key++;
  40. if (c == '\0') {
  41. key--;
  42. return (-1);
  43. }
  44. place = strchr(optstring, c);
  45. if (place == NULL || c == ':') {
  46. fprintf(stderr, "%s: unknown option %c\n", argv[0], c);
  47. return ('?');
  48. }
  49. place++;
  50. if (*place == ':') {
  51. if (optind < argc) {
  52. optarg = argv[optind];
  53. optind++;
  54. } else {
  55. fprintf(stderr, "%s: %c argument missing\n",
  56. argv[0], c);
  57. return ('?');
  58. }
  59. }
  60. return (c);
  61. }