manatttta
manatttta

Reputation: 3124

Calling fread inside for loop fails

I have the following code (solely for benchmark purposes).

The code consists of creating a simple char array, dumping it to a file, and then reading it inside a for loop. How come that the read function fails due to failuer in fopen (fread returns NULL), but works if I comment out the for loop?

I am using Apple LLVM version 8.0.0 (clang-800.0.42.1), and compiling simply with 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;

}

Upvotes: 0

Views: 268

Answers (2)

Rishi
Rishi

Reputation: 1395

You can move the fopen statement outside the for loop, since there is only one file. You don't need to open it inside the loop.

Upvotes: 1

aghast
aghast

Reputation: 15310

You never close the file opened inside the for loop in your read function. You're running out of filehandles, most likely.

Upvotes: 4

Related Questions