long-options.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* Utility to accept --help and --version options as unobtrusively as possible.
  2. Copyright (C) 1993, 1994, 1998 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2, or (at your option)
  6. any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software Foundation,
  13. Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
  14. /* Written by Jim Meyering. */
  15. #if HAVE_CONFIG_H
  16. # include <config.h>
  17. #endif
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <getopt.h>
  21. #include "closeout.h"
  22. #include "long-options.h"
  23. static struct option const long_options[] =
  24. {
  25. {"help", no_argument, 0, 'h'},
  26. {"version", no_argument, 0, 'v'},
  27. {0, 0, 0, 0}
  28. };
  29. /* Process long options --help and --version, but only if argc == 2.
  30. Be careful not to gobble up `--'. */
  31. void
  32. parse_long_options (argc, argv, command_name, package, version, usage)
  33. int argc;
  34. char **argv;
  35. const char *command_name;
  36. const char *package;
  37. const char *version;
  38. void (*usage)(int);
  39. {
  40. int c;
  41. int saved_opterr;
  42. saved_opterr = opterr;
  43. /* Don't print an error message for unrecognized options. */
  44. opterr = 0;
  45. if (argc == 2
  46. && (c = getopt_long (argc, argv, "+", long_options, NULL)) != -1)
  47. {
  48. switch (c)
  49. {
  50. case 'h':
  51. (*usage) (0);
  52. case 'v':
  53. printf ("%s (%s) %s\n", command_name, package, version);
  54. close_stdout (); /* FIXME: output failure exit status
  55. should be settable via an arg. */
  56. exit (0);
  57. default:
  58. /* Don't process any other long-named options. */
  59. break;
  60. }
  61. }
  62. /* Restore previous value. */
  63. opterr = saved_opterr;
  64. /* Reset this to zero so that getopt internals get initialized from
  65. the probably-new parameters when/if getopt is called later. */
  66. optind = 0;
  67. }