View of xos/tests/getopt.c


XOS | Parent Directory | View | Download

/* Copyright (C) 2008  Emmanuel Varoquaux
 
   This file is part of XOS.
 
   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.
 
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
 
   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */
 
#include "getopt.h"
 
#include <error.h>
#include <stdio.h>
#include <stdlib.h>
 
int main(int argc, char **argv)
{
  static int flag;
  static struct option longopts[] = {
    {"help", no_argument, NULL, 'h'},
    {"arg", required_argument, &flag, 'a'},
    {"opt", optional_argument, &flag, 'o'},
    {"he", no_argument, &flag, 'h'},
    {"hey", no_argument, &flag, 'h'},
    {"u", no_argument, &flag, 'h'},
    {0, 0, 0, 0}
  };
 
  int longindex;
  int c;
  int i;
 
  printf("options:\n");
  while ((c = getopt_long(argc, argv, "abc:d::e", longopts, &longindex)) != -1)
    switch (c) {
    case 0:
      switch (flag) {
      case 'a':
        printf("  %s %s\n", longopts[longindex].name, optarg);
        break;
      case 'h':
        printf("  %s\n", longopts[longindex].name);
        break;
      case 'o':
        if (optarg)
          printf("  %s %s\n", longopts[longindex].name, optarg);
        else
          printf("  %s (no argument)\n", longopts[longindex].name);
        break;
      default:
        error(EXIT_FAILURE, 0, "Unexpected option: %c", c);
      }
      break;
    case 1:
      printf("  \\1 %s\n", optarg);
      break;
    case 'a':
    case 'b':
    case 'e':
    case 'h':
      printf("  %c\n", c);
      break;
    case 'c':
      printf("  %c %s\n", c, optarg);
      break;
    case 'd':
      if (optarg)
        printf("  %c %s\n", c, optarg);
      else
        printf("  %c (no argument)\n", c);
      break;
    case ':':
      printf("  %c (missing argument)\n", optopt);
      break;
    case '?':
      printf("  (illegal option %c)\n", optopt);
      break;
    default:
      error(EXIT_FAILURE, 0, "Unexpected option: %c", c);
    }
  printf("\n");
 
  printf("arguments:\n");
  while (optind < argc)
    printf("  %s\n", argv[optind++]);
  printf("\n");
 
  printf("argv:\n");
  i = 0;
  while (argv[i])
    printf("%s ", argv[i++]);
  printf("\n");
 
  return EXIT_SUCCESS;
}