为什么fread()停在一个0的字符串? [英] Why is fread() stopping at a string of 0s?

查看:264
本文介绍了为什么fread()停在一个0的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下二进制配置读取二进制文件

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

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

使用以下函数

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;
}

其中 BitArray 是只是我自己的位操纵类。问题是,对于我上面提到的bin文件,它只读取前三个0,就像这样

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

即使 fseek 找到了正确的文件大小。

even though fseek has found the correct file size.

至于为什么我需要字符串0,因为 00 00 00 1A 形成一个32位整数,这恰好小到可以留下三个 0x00 s。

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.

我怀疑文件开头的一串 0x00 被识别为 EOF ,所以我尝试在文件前填充一个字符,但它没有完全解决。

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.

可能导致什么这个?

推荐答案

在windows中,0x1A又名 ^ Z 结束了文件字符。您已在文本模式而不是二进制模式下打开文件。当您在Windows中以文本模式打开文件时,它将一直读到文件结尾或第一个 ^ Z 字符。

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.

rb传递给 fopen 而不是r以二进制模式打开文件。

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

这篇关于为什么fread()停在一个0的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆