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

柔情痞子 提交于 2019-12-24 03:05:21

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/10631948/why-is-fread-stopping-at-a-string-of-0s

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!