You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

109 lines
2.5 KiB

  1. /*
  2. * Copyright (c) 2003-2007 Jim Paris <jim@jtan.com>
  3. *
  4. * This is free software; you can redistribute it and/or modify it and
  5. * it is provided under the terms of version 2 of the GNU General Public
  6. * License as published by the Free Software Foundation; see COPYING.
  7. */
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include "opt.h"
  12. void
  13. opt_init (int *optind)
  14. {
  15. *optind = 0;
  16. }
  17. char
  18. opt_parse (int argc, char **argv, int *optind, char **optarg,
  19. struct options *opt)
  20. {
  21. char c;
  22. int i;
  23. (*optind)++;
  24. if (*optind >= argc)
  25. return 0;
  26. if (argv[*optind][0] == '-' &&
  27. argv[*optind][1] != '-' && argv[*optind][1] != 0)
  28. {
  29. /* Short option (or a bunch of 'em) */
  30. /* Save this and shift others over */
  31. c = argv[*optind][1];
  32. for (i = 2; argv[*optind][i] != 0; i++)
  33. argv[*optind][i - 1] = argv[*optind][i];
  34. argv[*optind][i - 1] = 0;
  35. if (argv[*optind][1] != 0)
  36. (*optind)--;
  37. /* Now find it */
  38. for (i = 0; opt[i].shortopt != 0; i++)
  39. if (opt[i].shortopt == c)
  40. break;
  41. if (opt[i].shortopt == 0)
  42. {
  43. fprintf (stderr, "Error: unknown option '-%c'\n", c);
  44. return '?';
  45. }
  46. if (opt[i].arg == NULL)
  47. return c;
  48. (*optind)++;
  49. if (*optind >= argc || (argv[*optind][0] == '-' &&
  50. argv[*optind][1] != 0))
  51. {
  52. fprintf (stderr, "Error: option '-%c' requires an "
  53. "argument\n", c);
  54. return '?';
  55. }
  56. (*optarg) = argv[*optind];
  57. return c;
  58. }
  59. else if (argv[*optind][0] == '-' &&
  60. argv[*optind][1] == '-' && argv[*optind][2] != 0)
  61. {
  62. /* Long option */
  63. for (i = 0; (c = opt[i].shortopt) != 0; i++)
  64. if (strcmp (opt[i].longopt, argv[*optind] + 2) == 0)
  65. break;
  66. if (opt[i].shortopt == 0)
  67. {
  68. fprintf (stderr, "Error: unknown option '%s'\n", argv[*optind]);
  69. return '?';
  70. }
  71. if (opt[i].arg == NULL)
  72. return c;
  73. (*optind)++;
  74. if (*optind >= argc || (argv[*optind][0] == '-' &&
  75. argv[*optind][1] != 0))
  76. {
  77. fprintf (stderr, "Error: option '%s' requires an "
  78. "argument\n", argv[*optind - 1]);
  79. return '?';
  80. }
  81. (*optarg) = argv[*optind];
  82. return c;
  83. }
  84. else
  85. {
  86. /* End of options */
  87. return 0;
  88. }
  89. }
  90. void
  91. opt_help (struct options *opt, FILE * out)
  92. {
  93. int i;
  94. int printed;
  95. for (i = 0; opt[i].shortopt != 0; i++)
  96. {
  97. fprintf (out, " -%c, --%s%n", opt[i].shortopt,
  98. opt[i].longopt, &printed);
  99. fprintf (out, " %-*s%s\n", 30 - printed,
  100. opt[i].arg ? opt[i].arg : "", opt[i].help);
  101. }
  102. }