Platform-dependent behavior of fread with large nitems parameter

116 views Asked by At

I created the test program below in an attempt to debug an issue in a larger system. The program attempts to fread a large chunk of data from a small file, but I've found that the behavior of the program differs across platforms.

Expected behavior

The behavior that I expect, and that I see on some platforms (e.g., Mac OS X, CentOS 6.4), is for the program to read N bytes (the size of the file) and then terminate with the EOF condition:

Read 2 bytes.
OK. EOF

Anomalous behavior

On some platforms (e.g., CentOS 6.6), the program reports 0 bytes read and fails with an error:

Read 0 bytes.
NOOOOOOOOOOOOOO!!!! Error: Operation not permitted

On these platforms, I can get the code to work as expected by reducing the chunk size "enough", but I'm not sure how to determine an acceptable size programmatically...

Questions

  • Am I using fread correctly?
  • Is there a more portable approach I should be using?
  • Any suggested workarounds?

Code

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

int main(int argc, char* argv[]) {
    FILE* file = fopen("test.txt", "rb");
    size_t chunk = 0x7FFFFFFF;
    char* buf = malloc(chunk);
    if (buf == NULL) {
        printf("malloc failed\n");
        return 1;
    }
    int count = fread(buf, 1, chunk, file);
    printf("Read %i bytes.\n", count);
    int eof = feof(file);
    if (eof) {
        printf("OK. EOF\n");
    }
    int err = ferror(file);
    if (err) {
        printf("NOOOOOOOOOOOOOO!!!! Error: %s\n", strerror(err));
        return 1;
    }
    free(buf);
    return 0;
}

For my test, I created test.txt with echo "a" >test.txt.

0

There are 0 answers