c - C中的函数getopt与char * const *指针
问题描述
我想让第三个参数成为可能,如下所示:(文件名在任何位置,像这样)
program -a 3 <filename> -b 6
program -a 3 -b 6 <filename>
我怎样才能做到这一点getopt
并将这个字符串保存在变量中file
?
int main(int argc, char *const *argv) {
int a = 0; int b = 0; int i = 0;
char *A; char *B;
char *file = NULL;
int c;opterr = 0;
while ((c = getopt (argc, argv, "a:b:")) != -1) {
switch (c) {
case 'a': a = 1; A = optarg; break;
case 'b': b = 1; B = optarg; break;
case '?':
if (optopt == 'c') fprintf (stderr, "Option -%c requires an argument.", optopt);
else if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c'.", optopt);
else fprintf (stderr,"Unknown option character `\\x%x'.",optopt);
default: file = optarg; break; }}
strcpy(&file,*(argv + i));
return 0;
}
解决方案
该getopt
函数期望所有参数都在所有非参数之前。所以处理program -a 3 <filename> -b 6
是不可能的getopt
。文件名必须在末尾,或者必须有一个与之关联的选项字母。
关于读取文件名,您将在 getopt 循环之后进行。该optind
变量包含下一个尚未处理的参数的索引,因此可以减去该值argc
并添加它以argv
处理从 0 开始的剩余参数。
argc -= optind;
argv += optind;
file = argv[0];
推荐阅读
- pascal - 随机在循环内无法正常工作
- docker - 使用 Dockerfile 复制文件
- ruby-on-rails - 如何将一个大的 rspec 文件分成更小的部分
- three.js - THREE.js 根据其两个面的“法线”向量设置矩形平行六面体旋转
- javascript - Chart.js 用颜色可视化随时间的变化
- c++ - 是否可以覆盖基类构造函数?
- c++ - Project Euler 问题5 分段错误:11
- reactjs - Recatjs fecth api 无法获取业务错误
- dialogflow-es - 更改登录默认文本
- c# - C#- 给定一个枚举名称作为字符串返回枚举的所有值