xref: /relibc/tests/unistd/getopt.c (revision ed19381547d66b76981ea1e4ff942c5a4da45ab7)
1 #include <unistd.h>
2 #include <stdio.h>
3 
4 #include "test_helpers.h"
5 
6 #define RUN(...) \
7     do { \
8         optind = 1; \
9         optarg = NULL; \
10         opterr = 1; \
11         optopt = -1; \
12         char *args_arr[] = { __VA_ARGS__ }; \
13         printf("result: %d\n", runner(sizeof(args_arr) / sizeof(args_arr[0]), args_arr)); \
14     } while (0)
15 
16 int runner(int argc, char *argv[]) {
17     int c;
18     int bflg = 0, aflg = 0, errflg = 0;
19     char *ifile = "";
20     char *ofile = "";
21 
22     while((c = getopt(argc, argv, ":abf:o:")) != -1) {
23         switch(c) {
24             case 'a':
25                 if(bflg)
26                     errflg++;
27                 else
28                     aflg++;
29                 break;
30             case 'b':
31                 if(aflg)
32                     errflg++;
33                 else
34                     bflg++;
35                 break;
36             case 'f':
37                 ifile = optarg;
38                 break;
39             case 'o':
40                 ofile = optarg;
41                 break;
42             case ':':
43                 printf("Option -%c requires an operand\n", optopt);
44                 errflg++;
45                 break;
46             case '?':
47                 printf("Unrecognized option: -%c\n", optopt);
48                 errflg++;
49         }
50     }
51     printf("bflg: %d\n", bflg);
52     printf("aflg: %d\n", aflg);
53     printf("errflg: %d\n", errflg);
54     printf("ifile: %s\n", ifile);
55     printf("ofile: %s\n", ofile);
56     if(errflg) {
57         printf("Usage: info goes here\n");
58         return 2;
59     }
60     return 0;
61 }
62 
63 int main(int argc, const char *argv[]) {
64     RUN("test", "-ao", "arg", "path", "path");
65     RUN("test", "-a", "-o", "arg", "path", "path");
66     RUN("test", "-o", "arg", "-a", "path", "path");
67     RUN("test", "-a", "-o", "arg", "--", "path", "path");
68     RUN("test", "-a", "-oarg", "path", "path");
69     RUN("test", "-aoarg", "path", "path");
70     RUN("test");
71 }
72