xref: /openbsd/regress/lib/libc/getopt/getopt-test.c (revision e5dd7070)
1 /* $OpenBSD: getopt-test.c,v 1.1 2020/03/23 03:01:21 schwarze Exp $ */
2 /*
3  * Copyright (c) 2020 Ingo Schwarze <schwarze@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 
21 /*
22  * Process command line options and arguments according to the
23  * optstring in the environment variable OPTS.  Write:
24  * OPT(c) for an option "-c" without an option argument
25  * OPT(carg) for an option "-c" with an option argument "arg"
26  * ARG(arg) for a non-option argument "arg"
27  * NONE(arg) for a non-option argument "arg" processed with OPTS =~ ^-
28  * ERR(?c) for an invalid option "-c", or one lacking an argument
29  * ERR(:c) for an option "-c" lacking an argument while OPTS =~ ^:
30  */
31 int
32 main(int argc, char *argv[])
33 {
34 	char	*optstring;
35 	int	 ch;
36 
37 	if ((optstring = getenv("OPTS")) == NULL)
38 		optstring = "";
39 
40 	opterr = 0;
41 	while ((ch = getopt(argc, argv, optstring)) != -1) {
42 		switch (ch) {
43 		case '\1':
44 			printf("NONE(%s)", optarg);
45 			break;
46 		case ':':
47 		case '?':
48 			printf("ERR(%c%c)", ch, optopt);
49 			break;
50 		default:
51 			printf("OPT(%c%s)", ch, optarg == NULL ? "" : optarg);
52 			break;
53 		}
54 	}
55 	while (optind < argc)
56 		printf("ARG(%s)", argv[optind++]);
57 	putchar('\n');
58 	return 0;
59 }
60