【发布时间】:2023-03-07 03:40:01
【问题描述】:
我正在尝试解析传递给我的程序的参数以在函数中使用它们。 参数的格式是:
emp -p one.txt two.txt three.bin -o file.emp
我想将 -p 之后的参数保存在 char **arg_pack 中,并将 -o 之后的参数保存在 char **arg_output 中。
这是我的部分代码:
#define OPTION_STRING "p:u:r:l:d:o:i:ah"
#define OP_ARG_PACK 'p'
extern char *optarg;
extern int optind, opterr, optopt;
char **arg_pack;
char **arg_output;
int arg_pack_count = 0;
int arg_output_count = 0;
while ((res = getopt(argc, argv, OPTION_STRING)) != -1 )
{
if (res == (int) OP_ARG_PACK)
{
int index = optind - 1;
arg_pack_count++;
while(index < argc)
{
*arg_pack = malloc(strlen(argv[index])+1 );
strcpy(arg_pack[index], argv[index]);
index++;
if ( (index<argc) && ((argv[index])[0] == '-') )
{
optind = index - 1;
break;
}
}
emp_pack(arg_pack,arg_output);
}
}
这给了我一个分段错误。这是为什么呢?
【问题讨论】:
-
你忘了问问题。
-
请注意,就
getopt()而言,-p选项后面只有一个文件名(因此在您的示例中,optarg将被设置为指向字符串"one.txt"调用)。假设您使用 GNUgetopt()函数,在处理了-o选项后,其他两个文件名将作为非选项参数提供。如果您使用该函数的经典版本(或者如果您在环境中设置 POSIXLY_CORRECT),则two.txt参数不是选项参数;它是第一个非选项参数,其他参数,包括-o,也是非选项参数。