我在让命令行参数正常工作时遇到问题。当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);
}
这里显然有一些可怕的错误,但似乎找不到它。
答案 0 :(得分:2)
关于-o复制到-t,您忘记在案例结尾放置break;
。
另外,我会删除argc
检查。让getopt
发挥其魔力。您可以在解析结束时检查是否已设置所有必需选项。您还可以检查未知参数。