繁体   English   中英

在 cpp 中读取二进制文件有问题吗?

[英]Problem with reading a binary file in cpp?

我有一个名为“input.bin”的二进制文件,其中每个字符都是 4 位。 该文件包含此类数据:

0f00 0004 0018 0000 a040 420f 0016 030b
0000 8000 0000 0000 0000 0004 0018 0000

其中 0f 是第一个字节。

我想读取这些数据并这样做,我使用以下代码:

#include <string>
#include <iostream>
#include <fstream>

int main()
{
      char buffer[100];
      std::ifstream myFile ("input.bin", std::ios::in | std::ios::binary);
      myFile.read (buffer, 100);

      if (!myFile.read (buffer, 100)) {
        std::cout << "Could not open the required file\n";
      }
      else
      {
        for (int i = 0; i < 4; i++)
        {
          std::cout << "buffer[" << i << "] = " << static_cast<unsigned>(buffer[i]) << std::endl;
        }
        myFile.close();
      }
    return 0;
}

目前我只打印四个字节的数据,当我运行它时,我得到这个 output:

buffer[0] = 0
buffer[1] = 24
buffer[2] = 0
buffer[3] = 0

为什么它不打印 0f 的值,而只在索引 1 中打印 18 的值,而实际上它在索引 6 处?

问题就在这里

myFile.read (buffer, 100);

if (!myFile.read (buffer, 100)) {

你读了两次,因此忽略了前 100 个字节(如果它们超过 100 个)。

删除第一个read ,或将条件更改为if (!myFile)

您将数据的内容打印为字符 前四个字节都不是真正可打印的字符。

您需要将它们打印为(无符号)整数:

// Unsigned bytes to avoid possible sign extensions in conversions
unsigned char buffer[100];

...

// Convert the bytes to unsigned int for printing their numerical values
std::cout << "buffer[" << i << "] = " << static_cast<unsigned>(buffer[i]) << '\n';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM