long-options.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 <getopt.h>
  20. #include "closeout.h"
  21. #include "long-options.h"
  22. static struct option const long_options[] =
  23. {
  24. {"help", no_argument, 0, 'h'},
  25. {"version", no_argument, 0, 'v'},
  26. {0, 0, 0, 0}
  27. };
  28. /* Process long options --help and --version, but only if argc == 2.
  29. Be careful not to gobble up `--'. */
  30. void
  31. parse_long_options (argc, argv, command_name, package, version, usage)
  32. int argc;
  33. char **argv;
  34. const char *command_name;
  35. const char *package;
  36. const char *version;
  37. void (*usage)();
  38. {
  39. int c;
  40. int saved_opterr;
  41. saved_opterr = opterr;
  42. /* Don't print an error message for unrecognized options. */
  43. opterr = 0;
  44. if (argc == 2
  45. && (c = getopt_long (argc, argv, "+", long_options, NULL)) != -1)
  46. {
  47. switch (c)
  48. {
  49. case 'h':
  50. (*usage) (0);
  51. case 'v':
  52. printf ("%s (%s) %s\n", command_name, package, version);
  53. close_stdout (); /* FIXME: output failure exit status
  54. should be settable via an arg. */
  55. exit (0);
  56. default:
  57. /* Don't process any other long-named options. */
  58. break;
  59. }
  60. }
  61. /* Restore previous value. */
  62. opterr = saved_opterr;
  63. /* Reset this to zero so that getopt internals get initialized from
  64. the probably-new parameters when/if getopt is called later. */
  65. optind = 0;
  66. }