c - 在 c 中发明一个简单的参数解析器

标签 c

我知道我可以只使用 getopt 或其他库来处理这些东西,但我正在重新发明轮子。我不想只是坐在这里认为“get opt 只是自动为您解析选项”。

所以这是我创建的:

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

struct option_properties
{
    char *arglong;
    int tag;
};


int main(int argc, char **argv){

    struct option_properties options[] =
    {
        {"--input",  0},
        {"--output", 1},
        {"NULL", 2}
    };

    int i;
    int flag;
    int k = 1;
    for (; k < argc; k++){ //part 0
        printf("%d\n", k);
        for (i = 0; i < 3; i++){ // part 1
        if (!strcmp(argv[k], options[i].arglong)){ // part 2
                switch (options[i].tag) //part 3
                    {
                    case 0:
                        printf("argument input: %s\n", argv[k+1]);
                        break;
                    case 1:

                        printf("argument output: %s\n", argv[k+1]);
                        break;
                    default:
                        break;

                    }
                break;              
            }
        }       
    }
}

struct option_properties 是一个结构,包含了某个选项的标签。

struct option_properties options[] 包含可用选项及其编号标签。此数字标签稍后可用于 for 阶梯。

第0部分:从k开始计数到argc

第 1 部分:我们将扫描 struct option_properties option[]。注意:它的大小是 3。

第 2 部分:比较 options[i].arglong 中是否存在选项 (argv[k])

第三部分:如果存在,则获取其编号标签,并执行与其相似的编号。

虽然这可以解析选项,但它无法检测无效选项(或在 options[] 中找不到的选项)。

我的大脑无法解决如何检测无效选项的问题。如果可以,请帮忙。

最佳答案

这里有一些建议:

  • 使用sizeof(options) / sizeof(struct option_properties)而不是 3 .
  • 使用 sizeof() , 你可以不用 {"NULL", 2} .
  • 移动int k = 1里面for() : for (int k = 1; k < argc; k++) .
  • 我强烈建议您停止使用 TAB 字符来缩进您的代码。将您的编辑器设置更改为 TAB-inserts-4-spaces。

然后要检查选项是否无效,您可以添加 int found = 0您设置为 1 的变量如果!strcmp(argv[k], options[i].arglong)是真的。然后你检查foundfor (i = 0; i < 3; i++)之后循环。

关于c - 在 c 中发明一个简单的参数解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58644348/

相关文章:

c++ - #在头文件或实现文件中导入

c - 传递数组或传递指针

c - 二结构一功能

java - 通过网络将 RSA 公钥从 C 发送到 Java

c - 合并排序出现段错误

c - 函数作为函数的参数

c - 非阻塞stdio

c - Xeon Phi 的 reduce 操作的内联组装

objective-c - 为什么不需要取消引用 NSString 指针?

c - C 中枚举类型变量的用途