cpp字节文件读取 [英] cpp byte file reading

查看:51
本文介绍了cpp字节文件读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用c ++中的fstream读取字节文件(目标:二进制数据格式反序列化).dat文件在HxD十六进制编辑器(bytes.dat)中如下所示:

Im trying to read a byte file with fstream in c++ (goal: binary data format deserialization). The dat file looks something like below in HxD Hex editor (bytes.dat):

但是将二进制文件读入char数组时出了点问题.这是一个mwe:

but something goes wrong when reading the binary file into a char array.. here is a mwe:

#include <iostream>
#include <fstream>
using namespace std;

int main (){
  ofstream outfile;
  outfile.open("bytes.dat", std::ios::binary);
  outfile << hex << (char) 0x77 << (char) 0x77 << (char) 0x77 << (char) 0x07 \
  << (char) 0x9C << (char) 0x04 << (char) 0x00 << (char) 0x00 << (char) 0x41 \
  << (char) 0x49 << (char) 0x44 << (char) 0x30 << (char) 0x00 << (char) 0x00 \
  << (char) 0x04 << (char) 0x9C;
  ifstream infile;
  infile.open("bytes.dat", ios::in | ios::binary);
  char bytes[16];
  for (int i = 0; i < 16; ++i)
  {
    infile.read(&bytes[i], 1);
    printf("%02X ", bytes[i]);
  }
}

但这显示在cout中(mingw编译):

but this shows in the cout (mingw compiled):

> g++ bytes.cpp -o bytes.exe

> bytes.exe 

6A 58 2E 76 FFFFFF9E 6A 2E 76 FFFFFFB0 1E 40 00 6C FFFFFFFF 28 00

我做错了什么.某些数组项中怎么可能有4个字节?

im doing something wrong. How is it possible that there 4 bytes in some of the array entries?

推荐答案

  • 使用二进制数据(二进制文件格式等)时,最好使用无符号整数类型,以避免符号扩展名转换.
  • 按照读写二进制数据的建议,最好使用 stream.read stream.write 函数(最好也按块进行读写).
  • 如果您需要存储固定的二进制数据,请使用 std :: array std :: vector ,如果您需要从文件中加载数据( std::vector 是默认设置)
    • When working with binary data (binary file format and like), it's better to work with unsigned integer type to avoid sign extension conversions.
    • As recommended when reading and writing binary data, better use stream.read and stream.write functions (it's better read and write by block too).
    • If you need to storage fixed binary data use std::array or std::vector, if you need to load data from file (std::vector is the default)
    • 固定代码:

      #include <iostream>
      #include <fstream>
      #include <vector>
      using namespace std;
      
      int main() {
          vector<unsigned char> bytes1{0x77, 0x77, 0x77, 0x07, 0x9C, 0x04, 0x00, 0x00,
                                      0x41, 0x49, 0x44, 0x30, 0x00, 0x00, 0x04, 0x9C};
          ofstream outfile("bytes.dat", std::ios::binary);
          outfile.write((char*)&bytes1[0], bytes1.size());
          outfile.close();
      
          vector<unsigned char> bytes2(bytes1.size(), 0);
          ifstream infile("bytes.dat", ios::in | ios::binary);
          infile.read((char*)&bytes2[0], bytes2.size());
          for (int i = 0; i < bytes2.size(); ++i) {
              printf("%02X ", bytes2[i]);
          }
      }
      

      这篇关于cpp字节文件读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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