c++ - std::fstream 似乎以不同的大小读取

标签 c++ file byte fstream

我正在使用 ubuntu 10.04 和 gcc。我有一个带有我自己的魔数(Magic Number)的二进制文件。当我读取文件时,魔数(Magic Number)不一样。流接缝是正确的。

写魔数(Magic Number):

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

读取魔数(Magic Number):

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 作为魔数(Magic Number)时,它没问题(如输出所示):

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())。

关于c++ - std::fstream 似乎以不同的大小读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9469361/

相关文章:

objective-c - 如何在 objective-c 中将字节值转换为 int

java - Java 将字节数组转换为字符串

C++ 如何基于部分特化创建 std::tuple 类型?

java - 系统找不到java中指定的文件

c++ - 在同一连接或拆分连接上流式传输视频和命令?

java - 从 JAR 中的资源文件夹加载属性

Android 使用 Intent Filter 获取打开 Activity 的文件

javascript - 如何在 JavaScript 中将 1's and 0' 的数组转换为 ByteArray 或 Integer

c++ - 正确处理全屏 OpenGL 应用程序中的 Alt Tab

c++ - 包含特定文件时可以抑制所有警告吗?