【发布时间】:2022-09-28 23:17:20
【问题描述】:
我有一个程序需要解析命令行参数并将它们传递给各种函数以执行不同的任务。
一些可能的选项和可能的论点是:
-a <source> <destination>-b <filename>-p --num <number>-r --identical <source> <destination>-
-g --alphabetical <destination>
如您所见,各种选项非常多样化,不仅限于-f <x> 之类的简单选项,而是还具有各种参数和参数(例如-r)。
我研究了getopt_long/getopt,但这些并不能完全满足我的所有程序选项。例如我不能做-r --identical <source> <destination>。
所以我求助于解析自己:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
if (argc == 1)
{
fprintf(stderr,\"no args\");
return -1;
}
if (argc == 4)
{
if (strncmp(\"-a\", argv[1], 3) == 0)
{
a_function(argv[2], argv[3]);
}
}
else if (argc == 3)
{
if (strncmp(\"-b\", argv[1], 3) == 0)
{
another_func(argv[2]);
}
}
return 0;
}
上面的程序依赖于提供的参数的数量,我的问题是:有没有更有效/更干净的方法来解析参数(特别是我上面定义的那些),因为如果我继续,那么我的程序将有一个巨大的 @ 列表987654333@ 语句,看起来一点也不干净。如果有更好和更有效的方法,我将不胜感激在实施它方面的一些帮助。
-
抱歉,错误的链接:stackoverflow.com/questions/3939157/c-getopt-multiple-valueGoTTimw 对此问题的明确回答与您的示例相同: --identical <source> <destination> 其中 --identical 有两个参数。
标签: c arguments command-line-arguments argv argc