2010-05-26 11 views
13

me he dado cuenta del 'estilo' básico de la mayoría de las aplicaciones principales de GNU mediante el cual los argumentos son:Biblioteca para analizar argumentos ¿estilo GNU?

  • --longoption
  • --longoption=value o --longoption value
  • -abcdefg (múltiples opciones)
  • -iuwww-data (opción i, u = www-data)

Ellos siguen el estilo anterior. Quiero evitar escribir un analizador de argumentos si hay una biblioteca que hace esto usando el estilo anterior. ¿Hay uno que conozcas?

Respuesta

14

getopt_long hará el trabajo, aquí es un ejemplo de http://www.gnu.org/s/libc/manual/html_node/Getopt-Long-Option-Example.html

#include <stdio.h> 
#include <stdlib.h> 
#include <getopt.h> 

/* Flag set by ‘--verbose’. */ 
static int verbose_flag; 

int 
main (argc, argv) 
     int argc; 
     char **argv; 
{ 
    int c; 

    while (1) 
    { 
     static struct option long_options[] = 
     { 
      /* These options set a flag. */ 
      {"verbose", no_argument,  &verbose_flag, 1}, 
      {"brief", no_argument,  &verbose_flag, 0}, 
      /* These options don't set a flag. 
       We distinguish them by their indices. */ 
      {"add",  no_argument,  0, 'a'}, 
      {"append", no_argument,  0, 'b'}, 
      {"delete", required_argument, 0, 'd'}, 
      {"create", required_argument, 0, 'c'}, 
      {"file", required_argument, 0, 'f'}, 
      {0, 0, 0, 0} 
     }; 
     /* getopt_long stores the option index here. */ 
     int option_index = 0; 

     c = getopt_long (argc, argv, "abc:d:f:", 
         long_options, &option_index); 

     /* Detect the end of the options. */ 
     if (c == -1) 
     break; 

     switch (c) 
     { 
     case 0: 
      /* If this option set a flag, do nothing else now. */ 
      if (long_options[option_index].flag != 0) 
      break; 
      printf ("option %s", long_options[option_index].name); 
      if (optarg) 
      printf (" with arg %s", optarg); 
      printf ("\n"); 
      break; 

     case 'a': 
      puts ("option -a\n"); 
      break; 

     case 'b': 
      puts ("option -b\n"); 
      break; 

     case 'c': 
      printf ("option -c with value `%s'\n", optarg); 
      break; 

     case 'd': 
      printf ("option -d with value `%s'\n", optarg); 
      break; 

     case 'f': 
      printf ("option -f with value `%s'\n", optarg); 
      break; 

     case '?': 
      /* getopt_long already printed an error message. */ 
      break; 

     default: 
      abort(); 
     } 
    } 

    /* Instead of reporting ‘--verbose’ 
     and ‘--brief’ as they are encountered, 
     we report the final status resulting from them. */ 
    if (verbose_flag) 
    puts ("verbose flag is set"); 

    /* Print any remaining command line arguments (not options). */ 
    if (optind < argc) 
    { 
     printf ("non-option ARGV-elements: "); 
     while (optind < argc) 
     printf ("%s ", argv[optind++]); 
     putchar ('\n'); 
    } 

    exit (0); 
} 
+0

Pero si no tiene libc ... –

4

GNU proporciona getopt_long, a pesar de que en realidad recomiendan argp. Consulte el manual de GNU libc entry on parsing arguments.

+0

Pero eso es parte libc y no una biblioteca independiente. –

+0

@Dirk Eddelbuettel La pregunta menciona explícitamente el estilo de GNU, así que no estoy seguro de que sea un problema. –

+0

Hank: OP pidió una biblioteca en el título, no está claro si puede y quiere acceder a libc. Si está en Linux, está bien. Si él quiere una biblioteca portátil independiente, entonces su respuesta no ayuda. Pero solo el OP puede decir :) –

2

De vuelta en el día la gente simplemente envasados ​​getopt.c y getopt.h con sus fuentes.

Aquí hay una empresa del Google Code query. Puede usar eso si no quiere depender de GNU libc porque puede necesitar esto en un sistema operativo diferente. Pero si usted está en Linux, entonces libc ya se lo da a usted como lo sugirieron las otras respuestas.

+0

El enlace a la consulta de Google Code está muerto. – gbmhunter

+0

Google Code fue eliminado por Google hace uno o dos años. –

1

Google de código abierto tiene la biblioteca google-gflags, una biblioteca bandera analizador de la línea de comandos ..

yo sepa, no ofrece una versión "larga y corta" de cada indicador (por lo que no se puede combinar en múltiples opciones "-aeiou"), pero es trivial de usar y no requiere una lista centralizada de banderas.

Cuestiones relacionadas