Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

121 righe
2.9 KiB

  1. /*
  2. * TOIlet The Other Implementation’s letters
  3. * Copyright (c) 2002-2010 Sam Hocevar <sam@hocevar.net>
  4. * All Rights Reserved
  5. *
  6. * This program is free software. It comes without any warranty, to
  7. * the extent permitted by applicable law. You can redistribute it
  8. * and/or modify it under the terms of the Do What The Fuck You Want
  9. * To Public License, Version 2, as published by Sam Hocevar. See
  10. * http://sam.zoy.org/wtfpl/COPYING for more details.
  11. */
  12. /*
  13. * mygetopt.c: getopt_long reimplementation
  14. */
  15. #include "config.h"
  16. #if defined HAVE_STDINT_H
  17. # include <stdint.h>
  18. #elif defined HAVE_INTTYPES_H
  19. # include <inttypes.h>
  20. #endif
  21. #include <stdio.h>
  22. #include <string.h>
  23. #include "mygetopt.h"
  24. int myoptind = 1;
  25. char *myoptarg = NULL;
  26. /* XXX: this getopt_long implementation should not be trusted for other
  27. * applications without any serious peer reviewing. It “just works” with
  28. * zzuf but may fail miserably in other programs. */
  29. int mygetopt(int argc, char * const _argv[], const char *optstring,
  30. const struct myoption *longopts, int *longindex)
  31. {
  32. char **argv = (char **)(uintptr_t)_argv;
  33. char *flag;
  34. int i;
  35. if(myoptind >= argc)
  36. return -1;
  37. flag = argv[myoptind];
  38. if(flag[0] == '-' && flag[1] != '-')
  39. {
  40. char *tmp;
  41. int ret = flag[1];
  42. if(ret == '\0')
  43. return -1;
  44. tmp = strchr(optstring, ret);
  45. if(!tmp || ret == ':')
  46. return '?';
  47. myoptind++;
  48. if(tmp[1] == ':')
  49. {
  50. if(flag[2] != '\0')
  51. myoptarg = flag + 2;
  52. else
  53. myoptarg = argv[myoptind++];
  54. return ret;
  55. }
  56. if(flag[2] != '\0')
  57. {
  58. flag[1] = '-';
  59. myoptind--;
  60. argv[myoptind]++;
  61. }
  62. return ret;
  63. }
  64. if(flag[0] == '-' && flag[1] == '-')
  65. {
  66. if(flag[2] == '\0')
  67. return -1;
  68. for(i = 0; longopts[i].name; i++)
  69. {
  70. size_t l = strlen(longopts[i].name);
  71. if(strncmp(flag + 2, longopts[i].name, l))
  72. continue;
  73. switch(flag[2 + l])
  74. {
  75. case '=':
  76. if(!longopts[i].has_arg)
  77. goto bad_opt;
  78. if(longindex)
  79. *longindex = i;
  80. myoptind++;
  81. myoptarg = flag + 2 + l + 1;
  82. return longopts[i].val;
  83. case '\0':
  84. if(longindex)
  85. *longindex = i;
  86. myoptind++;
  87. if(longopts[i].has_arg)
  88. myoptarg = argv[myoptind++];
  89. return longopts[i].val;
  90. default:
  91. break;
  92. }
  93. }
  94. bad_opt:
  95. fprintf(stderr, "%s: unrecognized option `%s'\n", argv[0], flag);
  96. return '?';
  97. }
  98. return -1;
  99. }