Back to index

glibc  2.9
tstgetopt.c
Go to the documentation of this file.
00001 #include <getopt.h>
00002 #include <stdio.h>
00003 #include <string.h>
00004 #include <unistd.h>
00005 
00006 int
00007 main (int argc, char **argv)
00008 {
00009   static const struct option options[] =
00010     {
00011       {"required", required_argument, NULL, 'r'},
00012       {"optional", optional_argument, NULL, 'o'},
00013       {"none",     no_argument,       NULL, 'n'},
00014       {"color",    no_argument,       NULL, 'C'},
00015       {"colour",   no_argument,       NULL, 'C'},
00016       {NULL,       0,                 NULL, 0 }
00017     };
00018 
00019   int aflag = 0;
00020   int bflag = 0;
00021   char *cvalue = NULL;
00022   int Cflag = 0;
00023   int nflag = 0;
00024   int index;
00025   int c;
00026   int result = 0;
00027 
00028   while ((c = getopt_long (argc, argv, "abc:", options, NULL)) >= 0)
00029     switch (c)
00030       {
00031       case 'a':
00032        aflag = 1;
00033        break;
00034       case 'b':
00035        bflag = 1;
00036        break;
00037       case 'c':
00038        cvalue = optarg;
00039        break;
00040       case 'C':
00041        ++Cflag;
00042        break;
00043       case '?':
00044        fputs ("Unknown option.\n", stderr);
00045        return 1;
00046       default:
00047        fprintf (stderr, "This should never happen!\n");
00048        return 1;
00049 
00050       case 'r':
00051        printf ("--required %s\n", optarg);
00052        result |= strcmp (optarg, "foobar") != 0;
00053        break;
00054       case 'o':
00055        printf ("--optional %s\n", optarg);
00056        result |= optarg == NULL || strcmp (optarg, "bazbug") != 0;
00057        break;
00058       case 'n':
00059        puts ("--none");
00060        nflag = 1;
00061        break;
00062       }
00063 
00064   printf ("aflag = %d, bflag = %d, cvalue = %s, Cflags = %d, nflag = %d\n",
00065          aflag, bflag, cvalue, Cflag, nflag);
00066 
00067   result |= (aflag != 1 || bflag != 1 || cvalue == NULL
00068             || strcmp (cvalue, "foobar") != 0 || Cflag != 3 || nflag != 1);
00069 
00070   for (index = optind; index < argc; index++)
00071     printf ("Non-option argument %s\n", argv[index]);
00072 
00073   result |= optind + 1 != argc || strcmp (argv[optind], "random") != 0;
00074 
00075   return result;
00076 }