programa por parametros linea ejecutar con compilar compilador como comandos argumentos c linux arguments

por - main en c



Pase argumentos al programa C desde la línea de comandos (6)

Considera usar getopt_long() . Permite opciones cortas y largas en cualquier combinación.

#include <stdio.h> #include <stdlib.h> #include <getopt.h> /* Flag set by `--verbose''. */ static int verbose_flag; int main (int argc, char *argv[]) { while (1) { static struct option long_options[] = { /* This option set a flag. */ {"verbose", no_argument, &verbose_flag, 1}, /* These options don''t set a flag. We distinguish them by their indices. */ {"blip", no_argument, 0, ''b''}, {"slip", no_argument, 0, ''s''}, {0, 0, 0, 0} }; /* getopt_long stores the option index here. */ int option_index = 0; int c = getopt_long (argc, argv, "bs", 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 ''b'': puts ("option -b/n"); break; case ''s'': puts ("option -s/n"); break; case ''?'': /* getopt_long already printed an error message. */ break; default: abort (); } } 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''); } return 0; }

Relacionado:

Así que estoy en Linux y quiero que un programa acepte argumentos cuando lo ejecuta desde la línea de comando.

Por ejemplo,

./myprogram 42 -b -s

Entonces, el programa almacenaría ese número 42 como int y ejecutaría ciertas partes de código dependiendo de qué argumentos tenga, como -b o -s.


Echa un vistazo a la biblioteca getopt; es casi el estándar de oro para este tipo de cosas.


En C, esto se hace usando argumentos pasados ​​a su función main() :

int main(int argc, char *argv[]) { int i = 0; for (i = 0; i < argc; i++) { printf("argv[%d] = %s/n", i, argv[i]); } return 0; }

Se puede encontrar más información en línea, como este Argumentos al artículo principal .


En lugar de getopt() , también puede considerar el uso de argp_parse() (una interfaz alternativa a la misma biblioteca).

Desde libc manual :

getopt es más estándar (la versión de solo opción corta es parte del estándar POSIX), pero usar argp_parse es a menudo más fácil, tanto para estructuras de opciones muy simples como muy complejas, porque hace más trabajo sucio para ti.

Pero siempre estuve feliz con el getopt estándar.

NB GNU getopt con getopt_long es GNU LGPL.


Otros han golpeado este en la cabeza:

  • los argumentos estándar a main(int argc, char **argv) dan acceso directo a la línea de comando (después de que el shell lo ha triturado y tokenizado)
  • hay una instalación muy estándar para analizar la línea de comando: getopt() y getopt_long()

pero como has visto, el código para usarlos es un poco prolijo, y bastante idóneo. Generalmente lo alejo de la vista con algo como:

typedef struct options_struct { int some_flag; int other_flage; char *use_file; } opt_t; /* Parses the command line and fills the options structure, * returns non-zero on error */ int parse_options(opt_t *opts, int argc, char **argv);

Luego, lo primero en main:

int main(int argc, char **argv){ opt_t opts; if (parse_options(&opts,argc,argv)){ ... } ... }

O puede usar una de las soluciones sugeridas en Argument-parsing helpers para C / UNIX .


Puedes usar getopt .

#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main (int argc, char **argv) { int bflag = 0; int sflag = 0; int index; int c; opterr = 0; while ((c = getopt (argc, argv, "bs")) != -1) switch (c) { case ''b'': bflag = 1; break; case ''s'': sflag = 1; break; case ''?'': if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c''./n", optopt); else fprintf (stderr, "Unknown option character `//x%x''./n", optopt); return 1; default: abort (); } printf ("bflag = %d, sflag = %d/n", bflag, sflag); for (index = optind; index < argc; index++) printf ("Non-option argument %s/n", argv[index]); return 0; }