我在让命令行参数正常工作时遇到问题。当argc
大于 3 时,参数似乎失败了,之后你只能让它们工作,如果你写-fwhatever而不是-f 不管它应该是什么。-t 也复制 -o 的值。
int main(int argc,char **argv)
{
int c;
/* Are we in root? */
if(geteuid() !=0)
{
printf("Root access is required to run this program. \n");
exit(0);
}
/* How do we use the program */
if ((argc < 6) || (argc > 8))
{
usage(argv[0]);
exit (0);
}
while (1)
{
static struct option long_options[] =
{
/* Options */
{"send", no_argument, 0, 's'},
{"recieve", no_argument, 0, 'r'},
{"file", required_argument, 0, 'f'},
{"data", required_argument, 0, 'd'},
{"destip", required_argument, 0, 'i'},
{"destport", required_argument, 0, 'p'},
{"sourceip", required_argument, 0, 'o'},
{"sourceport", required_argument, 0, 't'},
{0, 0, 0, 0}
};
int option_index = 0;
c = getopt_long (argc, argv, "srf:d:i:p:o:t:",
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 's':
puts ("option -s\n");
break;
case 'r':
puts ("option -r\n");
break;
case 'f':
printf ("option -f with value `%s'\n", optarg);
break;
case 'd':
printf ("option -d with value `%s'\n", optarg);
break;
case 'i':
printf ("option -i with value `%s'\n", optarg);
break;
case 'p':
printf ("option -p with value `%s'\n", optarg);
break;
case 'o':
printf ("option -o with value `%s'\n", optarg);
case 't':
printf ("option -t with value `%s'\n", optarg);
case '?':
/* Error message printed */
break;
default:
abort ();
}
}
/* 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');
}
getchar ();
exit (0);
}
这里显然有什么可怕的错误,但它似乎找不到它。