繁体   English   中英

如何缓冲从大文件读取的数据而无需换行符

[英]How to buffer data read from a large file without newlines

我正在从一个文件中读取,其中有数千个以纯文本格式写的浮点数,各部分之间用换行符分隔。 浮点数本身之间用空格隔开,有时用分号分隔(每组3个分隔)。 直到最后才出现换行符,一个未知(但可能成千上万)的字符后来出现。

我使用的语言是C

3Dmodel.txt
-----

Obj1 Vertice count=5842;
{
0.499507 -0.003674 0.699311; 0.454010 -0.075165 ... -0.022236 \n (newline)
}

我的问题是,从文件中提取字符串并将其存储到内存中的最佳方法是什么?

看来我无法使用fgets() ,因为换行符太远了,并且因为它可能在浮动中间停止读取,因此不完整。 将整个文件读入内存似乎不必要,尽管如果这是唯一的方法,这并不可怕,因为每个文件只有2MB至10MB。

它可能会在浮动中间结束阅读...

那不是一个问题fgets ,如果浮子板缺, fseek这种浮动的开始,并从那里继续,例如阅读:

/ *数据* /

1.23 2.12 3.24 98.88 78.243 3.34 3.4 23.5 54.5
7.8 9.0

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

int main(void)
{
    char s[16], *p, *q;
    double d;
    FILE *f;

    f = fopen("data", "r");
    if (f == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }
    while ((p = fgets(s, sizeof s, f)) != NULL) {
        while (1) {
            d = strtod(p, &q);
            if (p == q) break;
            if (*q == '\0') {
                /* cutted, must adjust */
                printf("Cutted at <%s>, adjusting ...\n", p);
                fseek(f, -strlen(p), SEEK_CUR);
                break;
            }
            printf("%f\n", d);
            p = q;
        }
    }
    fclose(f);
    return 0;
}

输出:

1.230000
2.120000
3.240000
98.880000
78.243000
Cutted at < 3.>, adjusting ...
3.340000
3.400000
23.500000
54.500000
7.800000
9.000000

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM