Why is fread() stopping at a string of 0s?
Asked Answered
P

1

2

I am trying to read a binary file with the following binary configuration

00 00 00 1A 79 20 83 DB 44 ...

using the following function

static BitArray getBitArray(string filename)
{
    FILE *fs = fopen(filename.data(),"r");
    fseek (fs , 0 , SEEK_END);
    unsigned long s = ftell (fs);
    rewind (fs);

    unsigned char *buffer = new unsigned char[s+1];

    fread(buffer,1,s,fs);

    BitArray bArray;
    for(int i=0; i<s; i++)
        bArray.add(buffer[i]);

    delete[] buffer;
    fclose(fs);
    return bArray;
}

where BitArray is just my own bit manipulating class. The problem is, for the bin file I mentioned above, it only reads the first three 0s, like this

00 00 00

even though fseek has found the correct file size.

As to why I need that string 0s, is because 00 00 00 1A forms a 32-bit integer, which happened to be small enough to leave three 0x00s.

I suspected that a string of 0x00s in the beginning of a file is recognized as EOF, so i tried padding a char in front of the file, but it didn't quite work out.

What could be causing this?

Plunge answered 17/5, 2012 at 8:5 Comment(1)
What is the return value of fread?Barthold
S
9

in windows, 0x1A a.k.a ^Z is the end-of-file character. You have opened the file in text mode rather than binary mode. When you open a file in text mode in windows it will read until end-of-file or the first ^Z character.

pass "rb" to fopen instead of "r" to open the file in binary mode.

Stationery answered 17/5, 2012 at 8:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.