表单的命令行输入:
exeName -a argumentA -b argumentB -c argumentC
需要将每个参数提取到相应的变量中(即 int a = argumentA 等)。
出现函数 getop() 用于查找命令行选项。
但是,我看不出如何在每个选项之后获得指向的指针(因此我可以在它之后提取参数)。
手册页中的这个引用听起来像是......但没有太多关于如何使用它的信息:
"If getopt() finds another option character, it returns that character, updating the external variable optind and a static variable nextchar"
如何使用 getop() 在每个命令行选项后设置指向参数的指针?
最佳答案
optarg
给出了指向 getopt() 扫描的当前选项的指针.如果你想要指向命令行上传递的每个参数的指针,那么你可以将它们存储在一个指针数组中,由 optarg
给出。
这是一个最小的工作示例:
#include #包括
int main (int argc, char **argv)
{
char *p = 0;
char *arr[5] = {0};
int i;
int c;
while ((c = getopt (argc, argv, "A:B:C:")) != -1)
switch (c)
{
case 'A':
arr[0] = optarg;
break;
case 'B':
arr[1] = optarg;
break;
case 'C':
arr[2] = optarg;
break;
default:
printf("Invalid option %c\n", c);
}
printf("A:%s B:%s C:%s", arr[0], arr[1], arr[2]);
return 0;
}
当然,当没有提供一个或多个选项时,您应该添加更多的错误检查。
关于c - 如何使用 GETOPT 在每个命令行选项后获取指向每个参数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24233135/