Blame manual/examples/testopt.c

Packit 6c4009
/* Example of Parsing Arguments with getopt.
Packit 6c4009
   Copyright (C) 1991-2018 Free Software Foundation, Inc.
Packit 6c4009
Packit 6c4009
   This program is free software; you can redistribute it and/or
Packit 6c4009
   modify it under the terms of the GNU General Public License
Packit 6c4009
   as published by the Free Software Foundation; either version 2
Packit 6c4009
   of the License, or (at your option) any later version.
Packit 6c4009
Packit 6c4009
   This program is distributed in the hope that it will be useful,
Packit 6c4009
   but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit 6c4009
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
Packit 6c4009
   GNU General Public License for more details.
Packit 6c4009
Packit 6c4009
   You should have received a copy of the GNU General Public License
Packit 6c4009
   along with this program; if not, if not, see <http://www.gnu.org/licenses/>.
Packit 6c4009
*/
Packit 6c4009
Packit 6c4009
/*@group*/
Packit 6c4009
#include <ctype.h>
Packit 6c4009
#include <stdio.h>
Packit 6c4009
#include <stdlib.h>
Packit 6c4009
#include <unistd.h>
Packit 6c4009
Packit 6c4009
int
Packit 6c4009
main (int argc, char **argv)
Packit 6c4009
{
Packit 6c4009
  int aflag = 0;
Packit 6c4009
  int bflag = 0;
Packit 6c4009
  char *cvalue = NULL;
Packit 6c4009
  int index;
Packit 6c4009
  int c;
Packit 6c4009
Packit 6c4009
  opterr = 0;
Packit 6c4009
/*@end group*/
Packit 6c4009
Packit 6c4009
/*@group*/
Packit 6c4009
  while ((c = getopt (argc, argv, "abc:")) != -1)
Packit 6c4009
    switch (c)
Packit 6c4009
      {
Packit 6c4009
      case 'a':
Packit 6c4009
        aflag = 1;
Packit 6c4009
        break;
Packit 6c4009
      case 'b':
Packit 6c4009
        bflag = 1;
Packit 6c4009
        break;
Packit 6c4009
      case 'c':
Packit 6c4009
        cvalue = optarg;
Packit 6c4009
        break;
Packit 6c4009
      case '?':
Packit 6c4009
        if (optopt == 'c')
Packit 6c4009
          fprintf (stderr, "Option -%c requires an argument.\n", optopt);
Packit 6c4009
        else if (isprint (optopt))
Packit 6c4009
          fprintf (stderr, "Unknown option `-%c'.\n", optopt);
Packit 6c4009
        else
Packit 6c4009
          fprintf (stderr,
Packit 6c4009
                   "Unknown option character `\\x%x'.\n",
Packit 6c4009
                   optopt);
Packit 6c4009
        return 1;
Packit 6c4009
      default:
Packit 6c4009
        abort ();
Packit 6c4009
      }
Packit 6c4009
/*@end group*/
Packit 6c4009
Packit 6c4009
/*@group*/
Packit 6c4009
  printf ("aflag = %d, bflag = %d, cvalue = %s\n",
Packit 6c4009
	  aflag, bflag, cvalue);
Packit 6c4009
Packit 6c4009
  for (index = optind; index < argc; index++)
Packit 6c4009
    printf ("Non-option argument %s\n", argv[index]);
Packit 6c4009
  return 0;
Packit 6c4009
}
Packit 6c4009
/*@end group*/