我有以下代码(仅用于基准测试)。
代码包括创建一个简单的char数组,将其转储到一个文件中,然后在for循环中读取它。
为什么read函数会因为failuer infopenfread返回NULL)而失败,但是如果我注释掉for循环,它就会工作?
我使用的是Apple LLVM版本8.0.0(clang-800.0.42.1),只需使用clang -o rw rw.cpp

int create(int, char**) {

    char a[256*256];
    for (int i = 0; i < 256*256; i++)
        a[i] = char(i);

    // Dump to File
    FILE* f = fopen("file.bin", "wb");
    fwrite(a, 256*256*sizeof(char), 1, f);
    fclose(f);

    return 0;
}



int read(int, char**) {

    // IF this loop is commented out, the code works. Otherwise fails
    for (int i = 0; i < 10000; i++) {

        char a[256 * 256];

        FILE* f = fopen("file.bin", "rb");

        // Fails at this assertion
        assert(f);

        fread(a, 256*256*sizeof(char), 1, f);

        for (int k = 0; k < 256 * 256; k++) {
                if (a[k] != char(k)) {
                    printf("Bad Value %d %d\n", k, a[k]);
                }
        }
    }

    return 0;

}

最佳答案

您永远不会关闭read函数中for循环中打开的文件。很可能你的文件句柄用完了。

关于c - 在内部为循环调用fread失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42180143/

10-11 23:03
查看更多