在c中读取时解析文件

parsing a file while reading in c

我正在尝试读取文件的每一行并将二进制值存储到适当的变量中。 我可以看到还有许多其他人在做类似事情的例子,我花了两天时间测试了我发现的不同方法,但仍然难以让我的版本按需要工作。

我有一个 txt 文件,格式如下:

in = 00000000000, out = 0000000000000000
in = 00000000001, out = 0000000000001111
in = 00000000010, out = 0000000000110011
......

我正在尝试使用 fscanf 来处理不需要的字符 "in = "、“,”和 "out = " 并只保留代表二进制值的字符。

我的目标是将二进制值的第一列,"in" 值存储到一个变量中 和二进制值的第二列,"out" 值到另一个缓冲区变量。

我已经设法让 fscanf 消耗 "in" 和 "out" 字符,但我还没有 能够弄清楚如何让它消耗“,”“=”字符。此外,我认为 fscanf 应该消耗白色 space 但它似乎也没有这样做。

除了通用的“%d、%s、%c……”之外,我似乎找不到任何完整的扫描仪可用指令列表,看来我需要更复杂的组合过滤掉我试图忽略的字符的指令数量比我知道的格式要多。

我需要一些帮助来解决这个问题。如果您能提供任何指导,我将不胜感激 提供帮助我了解如何正确过滤掉 "in = " 和 ", out = " 以及如何存储 将两列二进制字符分为两个单独的变量。

这是我目前正在使用的代码。我已经尝试使用 fgetc() 结合 fscanf() 对该代码进行其他迭代,但没有成功。

int main()
{
    FILE * f = fopen("hamming_demo.txt","r");
    char buffer[100];
    rewind(f);
    while((fscanf(f, "%s", buffer)) != EOF) {
        fscanf(f,"%[^a-z]""[^,]", buffer);
        printf("%s\n", buffer);
    }
    printf("\n");
    return 0;
}

我的代码输出如下:

 = 00000000000, 
 = 0000000000000000

 = 00000000001, 
 = 0000000000001111

 = 00000000010, 
 = 0000000000110011

感谢您的宝贵时间。

所以基本上你想过滤 '0''1'?在这种情况下 fgets 和一个简单的循环就足够了:只需计算 0 和 1 的数量并在末尾以 null 终止字符串:

#include <stdio.h>

int main(void)
{
    char str[50];
    char *ptr;

    // Replace stdin with your file
    while ((ptr = fgets(str, sizeof str, stdin)))
    {
        int count = 0;

        while (*ptr != '[=10=]')
        {
            if ((*ptr >= '0') && (*ptr <= '1'))
            {
                str[count++] = *ptr;
            }
            ptr++;
        }
        str[count] = '[=10=]';
        puts(str);
    }
}

scanf族函数据说是一个可怜的解析器,因为它对输入错误的容忍度不是很高。但是如果您确定输入数据的格式,它允许使用简单的代码。如果格式字符串中的 space 将收集所有空白字符,包括换行符或 none,那么这里唯一的魔法。您的代码可能会变成:

int main()
{
    FILE * f = fopen("hamming_demo.txt", "r");
    if (NULL == f) {                               // always test open
        perror("Unable to open input file");
        return 1;
    }
    char in[50], out[50];                          // directly get in and out
    // BEWARE: xscanf returns the number of converted elements and never EOF
    while (fscanf(f, " in = %[01], out = %[01]", in, out) == 2) {
        printf("%s - %s\n", in, out);
    }
    printf("\n");
    return 0;
}