fscanf 在行中间找到空白字段后无法正常工作

fscanf is not working properly once it find a empty field in middle of line

我正在尝试循环读取文件的每一行并将值存储在结构中。 当 fscanf 遇到一个空字符串时,它会读取所有内容直到行尾,并且该行中的其他字段被读取为零。有没有办法指定 fscanf 将 space 作为字段读取。 下面的例子,

File.db:

tick31486081-tick31486081.mtd ,00:00:00:00:01:0e-31486081 , ,0,0,245
tick31486096-tick31486107-video1.ts ,00:00:00:00:01:0e-31486081 , ,1155072,5005312,5005312
tick31486080-tick31486080.mtd ,00:00:00:00:01:0e-31486080 , ,0,0,271

读取数据后:

tick31486081-tick31486081.mtd ,       00:00:00:00:01:0e-31486081 ,                      **,0,0,245** ,0,0,0
tick31486096-tick31486107-video1.ts ,       00:00:00:00:01:0e-31486081 ,      **,1155072,5005312,5005312** ,0,0,0
tick31486080-tick31486080.mtd ,       00:00:00:00:01:0e-31486080 ,                      **,0,0,271** ,0,0,0

有什么方法可以解决这个问题而不忽略 space 读取字段?

FILE *fp = fopen (FILE, "r");
if (fp)
{
    int retval;
    int numRead = 0;
    while (numRead != EOF)
    {
        Node_t *node = calloc (1, sizeof(Node_t));
        if (node)
        {

            numRead = fscanf (fp, "%40s ,%30s ,%33s ,%d,%d,%d\n", 
                    node->name, node->reid, node->hash,
                    &node->startOffset, &node->stopOffset, &node->length);
            printf(" %s ,%s ,%s ,%d,%d,%d", 
                    node->name, node->reid, node->hash,
                    node->startOffset, node->stopOffset, node->length);

        }

    }

    retval = fclose (fp);

}

使用“%[^,],%[^,],%[^,],%d,%d,%d\n”作为格式说明符,从一开始就去掉逗号分隔符3 个字符串值。

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

int main()
{
    char name[250], name2[250], name3[250];
    int one, two, three;
    FILE *f;
    f = fopen("text.txt", "r");
    if(f) {
        int numRead = 0;
        while (numRead != EOF) {
            numRead = fscanf(f, "%[^,],%[^,],%[^,],%d,%d,%d\n", name, name2, name3, &one, &two, &three);
            printf("name:%s name2:%s name3:%s one:%d two:%d three:%d\n", name, name2, name3, one, two, three);
            printf("name:%d name2:%d name3:%d\n", (int) strlen(name), (int) strlen(name2), (int) strlen(name3));
        }

        fclose(f);
    }
    else {
        printf("failed to open file\n");
    }

    return 0;
}

我认为您也可以将 fscanf-format-specifier 中的 \n 替换为 space。

祝你好运!