将大量数组逐行存储在文件中会导致文件损坏

问题描述 投票:0回答:2

我在内存中存储了一个输入数组A,用于生成另一个更大的数组B。但是,由于B是一个巨大的数组,我并不是很想将其存储在内存中,而是保存将其本地存储到文件中(使用fwrite)。为此,我计算每次迭代i th行,并将其附加到输出文件中。这样,我只需要一次在内存中存储一​​行,最后,将创建一个输出文件,其中包含我需要的所有数据。

考虑到文件组成的项目数,输出文件的大小似乎合适。但是,当我尝试使用fread从输出文件中读取片段时(例如,检索前2000个项目),仅检索了前23个项目。

这是创建输出文件的主要功能:

void exportCovMatrix(char *outputString, double *inputStdMatrix, int colDim, int rowDim) {
    double *covRow = calloc(rowDim, sizeof(double));
    int i, j, n;
    FILE *output;
    fclose(fopen(outputString, "w"));
    output = fopen(outputString, "a");
    assert(covRow != NULL);
    assert(output != NULL);
    for (i = 0; i < rowDim; i++) {
        for (j = 0; j < rowDim; j++)
            covRow[j] = dotProduct(&inputStdMatrix[i * colDim], &inputStdMatrix[j * colDim], colDim);
        n = fwrite(covRow, sizeof(double), rowDim, output);
        assert(n == rowDim);
    }
    fclose(output);
    free(covRow);
}

这是另一个函数,它读取给定的输出文件:

double *calculateNextB(char* inputString, double* row, int dim){
    FILE* input = fopen(inputString, "r");
    int i, j;
    assert(input != NULL);
    for(i = 0; i <= dim; i++){
        j = fread(row, sizeof(double), dim, input);
        printf("%d items were read.\n", j);
    }
    ...
}

非常感谢您为解决此问题提供的帮助。谢谢!

c arrays file fwrite fread
2个回答
0
投票

您分别使用]打开文件>

fclose(fopen(outputString, "w"));

FILE* input = fopen(inputString, "r");

但是例如,here的解释

为了将文件作为二进制文件打开,模式字符串中必须包含“ b”字符​​。

((我知道它是C ++源代码,但是在某些系统中是正确的,尽管在很多POSIX系统中不是这样,如https://linux.die.net/man/3/fopen中所述)


0
投票

我以为文件很大。在32位系统上,与流相关的功能(fopen,fwrite等)仅限于2GiB。超过此大小,功能的作用未定义。请参考此页面。https://www.gnu.org/software/libc/manual/html_node/Opening-Streams.html#index-fopen64-931

© www.soinside.com 2019 - 2024. All rights reserved.