gpt4 book ai didi

c - 使用 C getopt 跟踪多个参数

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:34 25 4
gpt4 key购买 nike

我的问题基于之前的一个问题,该问题询问 C optget 如何处理多个值:C getopt multiple value

在我的例子中,我只有一个参数 -i,这是可选的。用户必须使用此语法:

/a.out -i file1 -i file2 -i file3

如果用户不提供-i标志,程序运行正常。用户可以提供无限数量的文件作为可选参数,例如

/a.out -i file1 -i file2 -i file3 -i file4 -i file5 ...

我从 getopt() while main() 中的语句开始:

char *input;  // ?? Now syntactically correct, but uninitialized?

while ((opt = getopt(argc, argv, "i:"))!= -1){
case 'i':
if (optarg == NULL){
input = NULL;
}
else{
strcpy(input, optarg);
break;
...
}

然后我会将这些可选参数传递给一个函数:

function1(char *required_arg, ...)

在上述情况下,它将是:

function1(required_arg, file1, file2, file3, file4, file5)

目前,我将input 定义为"file"。我的问题是,如何跟踪任意数量的可选参数以便稍后传递给函数?上面的代码是错误的,因为我正在为传递的每个 -i 参数重新定义 input

使用什么数据结构?

最佳答案

我建议的解决方案是在数组中传递文件名。该解决方案假定最大文件数为 10,最大文件名长度为 30。但类似地,我们可以提供允许任意数量文件的动态分配机会。

#include <stdio.h>
#include <unistd.h>
#include <string.h>

#define MAXLEN 30
#define MAXFILECOUNT 10
void print(int fileCount, char files[][MAXLEN+1]){
for(int i = 0; i < fileCount; i++){
printf("%s \n",files[i]);
}
}
int main(int argc, char **argv)
{
int opt;
char fileName[MAXFILECOUNT][MAXLEN+1];
int count = 0;

while ((opt = getopt(argc, argv, "i:")) != -1)
{
switch (opt)
{
case 'i':
snprintf(fileName[count++],MAXLEN,"%s",optarg);
break;
}
}
print(count,fileName);
return 0;
}

像这样调用程序

./a.out -i file1 -i file2

关于c - 使用 C getopt 跟踪多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47610155/

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