/contrib/ntp/libntp/getopt.c

https://bitbucket.org/freebsd/freebsd-head/ · C · 107 lines · 75 code · 16 blank · 16 comment · 37 complexity · 4afac7b1782cb29c8cdbd004a0fd8c92 MD5 · raw file

  1. /*
  2. * getopt - get option letter from argv
  3. *
  4. * This is a version of the public domain getopt() implementation by
  5. * Henry Spencer, changed for 4.3BSD compatibility (in addition to System V).
  6. * It allows rescanning of an option list by setting optind to 0 before
  7. * calling, which is why we use it even if the system has its own (in fact,
  8. * this one has a unique name so as not to conflict with the system's).
  9. * Thanks to Dennis Ferguson for the appropriate modifications.
  10. *
  11. * This file is in the Public Domain.
  12. */
  13. /*LINTLIBRARY*/
  14. #include <stdio.h>
  15. #include "ntp_stdlib.h"
  16. #ifdef lint
  17. #undef putc
  18. #define putc fputc
  19. #endif /* lint */
  20. char *ntp_optarg; /* Global argument pointer. */
  21. int ntp_optind = 0; /* Global argv index. */
  22. int ntp_opterr = 1; /* for compatibility, should error be printed? */
  23. int ntp_optopt; /* for compatibility, option character checked */
  24. static char *scan = NULL; /* Private scan pointer. */
  25. static const char *prog = "amnesia";
  26. /*
  27. * Print message about a bad option.
  28. */
  29. static int
  30. badopt(
  31. const char *mess,
  32. int ch
  33. )
  34. {
  35. if (ntp_opterr) {
  36. fputs(prog, stderr);
  37. fputs(mess, stderr);
  38. (void) putc(ch, stderr);
  39. (void) putc('\n', stderr);
  40. }
  41. return ('?');
  42. }
  43. int
  44. ntp_getopt(
  45. int argc,
  46. char *argv[],
  47. const char *optstring
  48. )
  49. {
  50. register char c;
  51. register const char *place;
  52. prog = argv[0];
  53. ntp_optarg = NULL;
  54. if (ntp_optind == 0) {
  55. scan = NULL;
  56. ntp_optind++;
  57. }
  58. if (scan == NULL || *scan == '\0') {
  59. if (ntp_optind >= argc
  60. || argv[ntp_optind][0] != '-'
  61. || argv[ntp_optind][1] == '\0') {
  62. return (EOF);
  63. }
  64. if (argv[ntp_optind][1] == '-'
  65. && argv[ntp_optind][2] == '\0') {
  66. ntp_optind++;
  67. return (EOF);
  68. }
  69. scan = argv[ntp_optind++]+1;
  70. }
  71. c = *scan++;
  72. ntp_optopt = c & 0377;
  73. for (place = optstring; place != NULL && *place != '\0'; ++place)
  74. if (*place == c)
  75. break;
  76. if (place == NULL || *place == '\0' || c == ':' || c == '?') {
  77. return (badopt(": unknown option -", c));
  78. }
  79. place++;
  80. if (*place == ':') {
  81. if (*scan != '\0') {
  82. ntp_optarg = scan;
  83. scan = NULL;
  84. } else if (ntp_optind >= argc) {
  85. return (badopt(": option requires argument -", c));
  86. } else {
  87. ntp_optarg = argv[ntp_optind++];
  88. }
  89. }
  90. return (c & 0377);
  91. }