gpt4 book ai didi

命令行参数不起作用。某种逻辑错误

转载 作者:行者123 更新时间:2023-11-30 14:24:40 26 4
gpt4 key购买 nike

我在使命令行参数正常工作时遇到问题。当 argc 高于 3 时,参数似乎会失败,之后只有写 -fwhatever 而不是 -fwhatever< 才能让它们起作用。/em> 应该如此。 -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);

}

这里显然有一些可怕的错误,但它似乎找不到它。

最佳答案

关于复制到 -t 的 -o,您忘记在 case 末尾添加 break;

另外,我会删除 argc 检查。让 getopt 发挥它的魔力。您可以在解析结束时检查是否设置了所有强制选项。您还可以检查未知参数。

关于命令行参数不起作用。某种逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11459660/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com