c - 检查特定的命令行参数,然后将它们分配给变量
问题描述
强制性的总菜鸟在这里。
我正在制作一个简单的 C 程序,它从一个简单函数的文件中读取一些变量。然而,我想要完成的是允许调用程序的人覆盖从文件中读取的值,如果他们在命令行参数中指定的话。我想要这样的东西:
char* filename;
int number;
...
readConfig(filename, number, ...);
if (argc > 1) {
// Check if the variables were in the args here, in some way
strcpy(filename, args[??]);
number = atoi(args[??]);
}
我希望程序被称为
program -filename="path/to/file.txt" -number=3
我发现我可以标记每个参数并将其与每个可分配变量匹配并丢弃其他变量,但我很确定有一种更优雅的方法可以做到这一点(也许使用 getopts?)
非常感谢你的帮助。
解决方案
我在geeksforgeeks上找到了这个:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int opt;
// put ':' in the starting of the
// string so that program can
//distinguish between '?' and ':'
while((opt = getopt(argc, argv, ":if:lrx")) != -1)
{
switch(opt)
{
case 'i':
case 'l':
case 'r':
printf("option: %c\n", opt);
break;
case 'f':
printf("filename: %s\n", optarg);
break;
case ':':
printf("option needs a value\n");
break;
case '?':
printf("unknown option: %c\n", optopt);
break;
}
}
// optind is for the extra arguments
// which are not parsed
for(; optind < argc; optind++){
printf("extra arguments: %s\n", argv[optind]);
}
return 0;
}
所以,当你通过时-f
,你还需要传递文件名,比如:./args -f filename
它会说:
$ ./a.out -f file.txt
filename: file.txt
当你通过-i
, -l
, or -r
, or-ilr
时,它会说:
$ ./a.out -ilr
option: i
option: l
option: r
如果你通过-f
但没有文件名,它会说选项需要参数。其他任何内容都将打印到额外的参数
因此,有了它,您可以向 getopts 添加选项、添加新案例、做一件事,例如:
getopts(argc, argv, ":fn:")
-f 文件名、-n 编号,非常简单
推荐阅读
- python - 为什么 VB Shell 函数不会停止 Python 代码执行窗口?
- react-native - 为什么在 react-native 中重新启动应用程序后状态栏不显示组件屏幕
- c++ - 如何使用 Apple M1 处理器在 macOS Big Sur 上安装 gcc 11.2.0
- makefile - “make”如何读取/解析具有百分比匹配目标与显式的 Makefile?
- python - 仅使用字符串作为键更改 Django 字段
- php - Doxygen 和 PHP 多行属性
- ios - 防止标签从侧面被切断 - TagsView
- vaadin - 如何在 FormLayout 中设置垂直对齐
- flutter - 如何仅在时间转换日期和时间?
- c++ - 将结构指针数组传递给函数