xgetopt.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //---------------------------------------------------------------------------------
  2. //
  3. // Little Color Management System
  4. // Copyright (c) 1998-2023 Marti Maria Saguer
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining
  7. // a copy of this software and associated documentation files (the "Software"),
  8. // to deal in the Software without restriction, including without limitation
  9. // the rights to use, copy, modify, merge, publish, distribute, sublicense,
  10. // and/or sell copies of the Software, and to permit persons to whom the Software
  11. // is furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
  18. // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  20. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  21. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  22. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. //
  24. //---------------------------------------------------------------------------------
  25. //
  26. // xgetopt.c -- loosely based on System V getopt()
  27. //
  28. // option ::= SW [optLetter]* [argLetter space* argument]
  29. //
  30. #include <string.h>
  31. #include <stdio.h>
  32. int xoptind = 1;
  33. char *xoptarg;
  34. static char *nextArg = NULL;
  35. #define SW '-'
  36. int xgetopt(int argc, char* argv[], char* optionS)
  37. {
  38. unsigned char ch;
  39. char* optP;
  40. if (argc > xoptind)
  41. {
  42. if (nextArg == NULL)
  43. {
  44. if ((nextArg = argv[xoptind]) == NULL || *(nextArg++) != SW) goto end_eof;
  45. }
  46. if ((ch = *(nextArg++)) == 0)
  47. {
  48. xoptind++;
  49. goto end_eof;
  50. }
  51. if (ch == ':' || (optP = strchr(optionS, ch)) == NULL)
  52. goto end_error;
  53. if (*(++optP) == ':')
  54. {
  55. xoptind++;
  56. if (*nextArg == 0)
  57. {
  58. if (argc <= xoptind) goto end_error;
  59. nextArg = argv[xoptind++];
  60. }
  61. xoptarg = nextArg;
  62. nextArg = NULL;
  63. }
  64. else
  65. {
  66. if (*nextArg == 0)
  67. {
  68. xoptind++;
  69. nextArg = NULL;
  70. }
  71. xoptarg = NULL;
  72. }
  73. return ch;
  74. }
  75. end_eof:
  76. xoptarg = nextArg = NULL;
  77. return EOF;
  78. end_error:
  79. xoptarg = NULL;
  80. return '?';
  81. }