getopt.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * This file is part of Libav.
  3. *
  4. * Libav 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. * Libav 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 Libav; 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. static int getopt(int argc, char *argv[], char *opts)
  38. {
  39. static int sp = 1;
  40. int c;
  41. char *cp;
  42. if (sp == 1)
  43. if (optind >= argc ||
  44. argv[optind][0] != '-' || argv[optind][1] == '\0')
  45. return EOF;
  46. else if (!strcmp(argv[optind], "--")) {
  47. optind++;
  48. return EOF;
  49. }
  50. optopt = c = argv[optind][sp];
  51. if (c == ':' || (cp = strchr(opts, c)) == NULL) {
  52. fprintf(stderr, ": illegal option -- %c\n", c);
  53. if (argv[optind][++sp] == '\0') {
  54. optind++;
  55. sp = 1;
  56. }
  57. return '?';
  58. }
  59. if (*++cp == ':') {
  60. if (argv[optind][sp+1] != '\0')
  61. optarg = &argv[optind++][sp+1];
  62. else if(++optind >= argc) {
  63. fprintf(stderr, ": option requires an argument -- %c\n", c);
  64. sp = 1;
  65. return '?';
  66. } else
  67. optarg = argv[optind++];
  68. sp = 1;
  69. } else {
  70. if (argv[optind][++sp] == '\0') {
  71. sp = 1;
  72. optind++;
  73. }
  74. optarg = NULL;
  75. }
  76. return c;
  77. }