lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame] | 1 | /* Example of Parsing Arguments with getopt. |
| 2 | Copyright (C) 1991-2015 Free Software Foundation, Inc. |
| 3 | |
| 4 | This program is free software; you can redistribute it and/or |
| 5 | modify it under the terms of the GNU General Public License |
| 6 | as published by the Free Software Foundation; either version 2 |
| 7 | of the License, or (at your option) any later version. |
| 8 | |
| 9 | This program is distributed in the hope that it will be useful, |
| 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | GNU General Public License for more details. |
| 13 | |
| 14 | You should have received a copy of the GNU General Public License |
| 15 | along with this program; if not, if not, see <http://www.gnu.org/licenses/>. |
| 16 | */ |
| 17 | |
| 18 | /*@group*/ |
| 19 | #include <ctype.h> |
| 20 | #include <stdio.h> |
| 21 | #include <stdlib.h> |
| 22 | #include <unistd.h> |
| 23 | |
| 24 | int |
| 25 | main (int argc, char **argv) |
| 26 | { |
| 27 | int aflag = 0; |
| 28 | int bflag = 0; |
| 29 | char *cvalue = NULL; |
| 30 | int index; |
| 31 | int c; |
| 32 | |
| 33 | opterr = 0; |
| 34 | /*@end group*/ |
| 35 | |
| 36 | /*@group*/ |
| 37 | while ((c = getopt (argc, argv, "abc:")) != -1) |
| 38 | switch (c) |
| 39 | { |
| 40 | case 'a': |
| 41 | aflag = 1; |
| 42 | break; |
| 43 | case 'b': |
| 44 | bflag = 1; |
| 45 | break; |
| 46 | case 'c': |
| 47 | cvalue = optarg; |
| 48 | break; |
| 49 | case '?': |
| 50 | if (optopt == 'c') |
| 51 | fprintf (stderr, "Option -%c requires an argument.\n", optopt); |
| 52 | else if (isprint (optopt)) |
| 53 | fprintf (stderr, "Unknown option `-%c'.\n", optopt); |
| 54 | else |
| 55 | fprintf (stderr, |
| 56 | "Unknown option character `\\x%x'.\n", |
| 57 | optopt); |
| 58 | return 1; |
| 59 | default: |
| 60 | abort (); |
| 61 | } |
| 62 | /*@end group*/ |
| 63 | |
| 64 | /*@group*/ |
| 65 | printf ("aflag = %d, bflag = %d, cvalue = %s\n", |
| 66 | aflag, bflag, cvalue); |
| 67 | |
| 68 | for (index = optind; index < argc; index++) |
| 69 | printf ("Non-option argument %s\n", argv[index]); |
| 70 | return 0; |
| 71 | } |
| 72 | /*@end group*/ |