Цикл должен содержать только переключатель. Обработайте остаточные аргументы в отдельном (не вложенном) цикле:
#include <stdio.h>
#include <getopt.h>
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"input", required_argument, 0, 'i'},
{"output", required_argument, 0, 'o'},
{"algorithm", required_argument, 0, 'a'},
{0, 0, 0, 0}
};
int main(int argc, char *argv[])
{
int opt;
int option_index = 0;
int i;
while ((opt = getopt_long(argc, argv, "hi:o:a:", long_options, &option_index)) != -1)
{
switch(opt)
{
case 'h': /* --help */
printf("--help flag\n");
break;
case 'i': /* --input */
printf("--input flag (%s)\n", optarg);
break;
case 'o': /* --output */
printf("--output flag (%s)\n", optarg);
break;
case 'a': /* --algorithm */
printf("--algorithm flag (%s)\n", optarg);
break;
default: /* ??? */
fprintf(stderr, "Invalid option %c\n", opt);
return 1;
}
}
for (i = optind; i < argc; i++)
printf("Process: %s\n", argv[i]);
return 0;
}
Есть способ заставить GNU getopt()
и getopt_long()
возвращать аргументы имени файла, как если бы они были опциями с 'letter' ^ A '\ 1'; используйте '-
' в качестве первого символа строки коротких опций и ловите '\1
' в переключателе; значение optarg
является именем файла.
#include <stdio.h>
#include <getopt.h>
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"input", required_argument, 0, 'i'},
{"output", required_argument, 0, 'o'},
{"algorithm", required_argument, 0, 'a'},
{0, 0, 0, 0}
};
int main(int argc, char *argv[])
{
int opt;
int option_index = 0;
int i;
while ((opt = getopt_long(argc, argv, "-hi:o:a:", long_options, &option_index)) != -1)
{
switch(opt)
{
case 'h': /* --help */
printf("--help flag\n");
break;
case 'i': /* --input */
printf("--input flag (%s)\n", optarg);
break;
case 'o': /* --output */
printf("--output flag (%s)\n", optarg);
break;
case 'a': /* --algorithm */
printf("--algorithm flag (%s)\n", optarg);
break;
case '\1':
printf("File: %s\n", optarg);
break;
default: /* ??? */
fprintf(stderr, "Invalid option %c\n", opt);
return 1;
}
}
for (i = optind; i < argc; i++)
printf("Process: %s\n", argv[i]);
return 0;
}
Однако вам нужен цикл после цикла обработки аргументов в случае, если ваш странный пользователь наберет:
program -- abc def
--
'завершает цикл while()
без обработки аргументов имени файла.