testopt.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* Example of Parsing Arguments with getopt.
  2. Copyright (C) 1991-2019 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU General Public License
  5. as published by the Free Software Foundation; either version 2
  6. of the License, or (at your option) 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, see <http://www.gnu.org/licenses/>.
  13. */
  14. /*@group*/
  15. #include <ctype.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <unistd.h>
  19. int
  20. main (int argc, char **argv)
  21. {
  22. int aflag = 0;
  23. int bflag = 0;
  24. char *cvalue = NULL;
  25. int index;
  26. int c;
  27. opterr = 0;
  28. /*@end group*/
  29. /*@group*/
  30. while ((c = getopt (argc, argv, "abc:")) != -1)
  31. switch (c)
  32. {
  33. case 'a':
  34. aflag = 1;
  35. break;
  36. case 'b':
  37. bflag = 1;
  38. break;
  39. case 'c':
  40. cvalue = optarg;
  41. break;
  42. case '?':
  43. if (optopt == 'c')
  44. fprintf (stderr, "Option -%c requires an argument.\n", optopt);
  45. else if (isprint (optopt))
  46. fprintf (stderr, "Unknown option `-%c'.\n", optopt);
  47. else
  48. fprintf (stderr,
  49. "Unknown option character `\\x%x'.\n",
  50. optopt);
  51. return 1;
  52. default:
  53. abort ();
  54. }
  55. /*@end group*/
  56. /*@group*/
  57. printf ("aflag = %d, bflag = %d, cvalue = %s\n",
  58. aflag, bflag, cvalue);
  59. for (index = optind; index < argc; index++)
  60. printf ("Non-option argument %s\n", argv[index]);
  61. return 0;
  62. }
  63. /*@end group*/