Kame
Kame

Reputation: 11

fread not working as expected on 64-bit iOS

I have a sample function below (written by C/C++). My problem is it's working fine on iOS 32 bit version, but on iOS 64 bit version (iPhone 5s or later) it can not run, the r value is always equals 0 on iOS 64 bit

I don't have more knowledges about this issue. Please help me !

long __loadData(FILE *f,UInt32 offset,size_t len,UInt8* d)
{
    if(f)
    {
        if (fseek(f, offset, SEEK_SET) < 0) return 11;
        size_t r = fread(d,1,len,f);
        return r - len;
    }
    return 1;
}

Upvotes: 0

Views: 821

Answers (1)

zaph
zaph

Reputation: 112855

Try:

size_t r = fread(d, (size_t)1, len, f);

I suspect that nitems is based on the architecture size but is declared as size_t:

size_t fread(void *restrict ptr, size_t size, size_t nitems, FILE *restrict stream);

Statements like this are hard to debug:

if (fseek(f, offset, SEEK_SET) < 0) return 11;

Instead, break it up:

long loadData(FILE *stream, UInt32 offset, size_t length, UInt8* data)
{
    if(stream) {
        int status = fseek(stream, offset, SEEK_SET);
        if (status == -1) {
            printf("fseek errno: %d", errno);
            return 11;
        }

        size_t bytesRead = fread(data, 1, length, stream);
        if (bytesRead == 0) {
            if (ferror(stream) {
                printf("fread ferror");
            }
            if (feof(stream) {
                printf("fread feof");
            }
        }
    }
    return 1;
}

Now you can step through and if there is an error the error number will printout.

In general write for clarity and do not ignore error messages. Better naming helps with comprehension, write for the future developer, it may even be you.

Note: Code was written in SO and not tested.

Upvotes: 1

Related Questions