bh_getopt.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (C) 2020 Ant Financial Services Group. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #ifndef __GNUC__
  6. #include "bh_getopt.h"
  7. #include <stdio.h>
  8. #include <string.h>
  9. char *optarg = NULL;
  10. int optind = 1;
  11. int
  12. getopt(int argc, char *const argv[], const char *optstring)
  13. {
  14. static int sp = 1;
  15. int opt;
  16. char *p;
  17. if (sp == 1) {
  18. if ((optind >= argc) || (argv[optind][0] != '-')
  19. || (argv[optind][1] == 0)) {
  20. return -1;
  21. }
  22. else if (!strcmp(argv[optind], "--")) {
  23. optind++;
  24. return -1;
  25. }
  26. }
  27. opt = argv[optind][sp];
  28. p = strchr(optstring, opt);
  29. if (opt == ':' || p == NULL) {
  30. printf("illegal option : '-%c'\n", opt);
  31. if (argv[optind][++sp] == '\0') {
  32. optind++;
  33. sp = 1;
  34. }
  35. return ('?');
  36. }
  37. if (p[1] == ':') {
  38. if (argv[optind][sp + 1] != '\0')
  39. optarg = &argv[optind++][sp + 1];
  40. else if (++optind >= argc) {
  41. printf("option '-%c' requires an argument :\n", opt);
  42. sp = 1;
  43. return ('?');
  44. }
  45. else {
  46. optarg = argv[optind++];
  47. }
  48. sp = 1;
  49. }
  50. else {
  51. if (argv[optind][++sp] == '\0') {
  52. sp = 1;
  53. optind++;
  54. }
  55. optarg = NULL;
  56. }
  57. return (opt);
  58. }
  59. #endif