getopt.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * This file is part of FFmpeg.
  3. *
  4. * FFmpeg is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * FFmpeg is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with FFmpeg; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. /*
  19. * This file was copied from the following newsgroup posting:
  20. *
  21. * Newsgroups: mod.std.unix
  22. * Subject: public domain AT&T getopt source
  23. * Date: 3 Nov 85 19:34:15 GMT
  24. *
  25. * Here's something you've all been waiting for: the AT&T public domain
  26. * source for getopt(3). It is the code which was given out at the 1985
  27. * UNIFORUM conference in Dallas. I obtained it by electronic mail
  28. * directly from AT&T. The people there assure me that it is indeed
  29. * in the public domain.
  30. */
  31. #include <stdio.h>
  32. #include <string.h>
  33. static int opterr = 1;
  34. static int optind = 1;
  35. static int optopt;
  36. static char *optarg;
  37. #undef fprintf
  38. static int getopt(int argc, char *argv[], char *opts)
  39. {
  40. static int sp = 1;
  41. int c;
  42. char *cp;
  43. if (sp == 1)
  44. if (optind >= argc ||
  45. argv[optind][0] != '-' || argv[optind][1] == '\0')
  46. return EOF;
  47. else if (!strcmp(argv[optind], "--")) {
  48. optind++;
  49. return EOF;
  50. }
  51. optopt = c = argv[optind][sp];
  52. if (c == ':' || (cp = strchr(opts, c)) == NULL) {
  53. fprintf(stderr, ": illegal option -- %c\n", c);
  54. if (argv[optind][++sp] == '\0') {
  55. optind++;
  56. sp = 1;
  57. }
  58. return '?';
  59. }
  60. if (*++cp == ':') {
  61. if (argv[optind][sp+1] != '\0')
  62. optarg = &argv[optind++][sp+1];
  63. else if(++optind >= argc) {
  64. fprintf(stderr, ": option requires an argument -- %c\n", c);
  65. sp = 1;
  66. return '?';
  67. } else
  68. optarg = argv[optind++];
  69. sp = 1;
  70. } else {
  71. if (argv[optind][++sp] == '\0') {
  72. sp = 1;
  73. optind++;
  74. }
  75. optarg = NULL;
  76. }
  77. return c;
  78. }