std::fstream似乎有不同的大小

std::fstream seems to read in different sizes

本文关键字:fstream std      更新时间:2023-10-16

我正在开发ubuntu 1004和一个gcc。我有一个二进制文件,里面有我自己的幻数。当我读取文件时,幻数是不一样的。溪流接缝正确。

书写神奇数字:

std::fstream chfile;
chfile.open(filename.c_str(), std::fstream::binary | std::fstream::out);
if (chfile.good())
{
    chfile << (unsigned char)0x02 << (unsigned char)0x46 << (unsigned char)0x8A << (unsigned char)0xCE;
    // other input
    chfile.close();
}

阅读魔术数字:

std::fstream chfile;
chfile.open(filename.c_str(), std::fstream::binary | std::fstream::in);
if (chfile.good())
{
    unsigned char a,b,c,d;
    chfile >> a;
    chfile >> b;
    chfile >> c;
    chfile >> d;
    printlnn("header must : " << (int)0x02 << ' ' << (int)0x46 << ' ' << (int)0x8A << ' ' << (int)0xCE); // macro for debugging output
    printlnn("header read : " << (int)a << ' ' << (int)b << ' ' << (int)c << ' ' << (int)d);
    chfile.close();
}

当我使用02 46 8A CE作为幻数时,它是可以的(正如输出所说):

header must : 2 70 138 206
header read : 2 70 138 206

但当我使用EA 50 0C C5时,输出为:

header must : 234 80 12 197
header read : 234 80 197 1

最后一个1是下一个输入的合法值。那么,为什么它们不同,我该如何解决呢?

在第二种情况下,operator>>跳过字符值12。operator>>12识别为空白,并跳过它,搜索下一个有效字符。

请尝试使用未格式化的输入操作(如chfile.read()chfile.get())。

您不应该将<<>>与二进制文件一起使用,它们用于格式化读取和写入
特别是,它们对空白进行特殊处理,如0xC(即formfeed),这使它们不适合二进制i/O。