Я не совсем понимаю, как я могу правильно обрабатывать аргументы командной строки в c, используя функцию getopt_long, я создаю этот код:
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
int main(int argc, char** argv) {
int next_option;
/* String of short options */
const char *short_options = "hl:k";
/* The array of long options */
const struct option long_options[] = {
{ "help", 0, NULL, 'h' },
{ "launch", 1, NULL, 'l' },
{ "kill", 0, NULL, 'k' },
{ NULL, 0, NULL, 0 }
};
do {
next_option = getopt_long(argc, argv, short_options, long_options, NULL);
switch (next_option) {
case 'h':
/* User requested help */
fprintf(stdout, "HELP\n");
break;
case 'l':
fprintf(stdout, "launching\n");
fprintf(stdout, "Want to launch on port %s\n",\
optarg);
break;
case 'k':
fprintf(stdout, "KILLING\n");
break;
case '?':
/* The user specified an invalid option */
fprintf(stdout, "Requested arg does not exist!\n");
exit(EXIT_FAILURE);
case -1:
/* Done with options */
break;
default:
/* Unexpected things */
fprintf(stdout, "I can't handle this arg!\n");
exit(EXIT_FAILURE);
}
} while(next_option != -1);
return (EXIT_SUCCESS);
}
И вывод странный, потому что мы можем передавать данные мусора какаргументы командной строки и моя программа не проверяют эти ошибки!Как я могу это исправить.
Пример выполнения:
$ ./command_line -h garbage
HELP
$ ./command_line --help garbage
HELP
$ ./command_line --launch 1200 garbage
launching
Want to launch on port 1200
$ ./command_line --lBADARG 1200
command_line: unrecognized option `--lBADARG'
Requested arg does not exist!
$ ./command_line -lBADARG 1200
launching
Want to launch on port BADARG
Спасибо за вашу помощь.