cpp字节文件读取

时间:2014-09-02 13:52:48

标签: c++ binary fstream

我试图用c ++中的fstream读取一个字节文件(目标:二进制数据格式反序列化)。在HxD Hex编辑器(bytes.dat)中,dat文件如下所示:

bytefile

但是在将二进制文件读入char数组时会出现问题..这是一个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编译):

> 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个字节?

1 个答案:

答案 0 :(得分:4)

  • 使用二进制数据(二进制文件格式等)时,最好使用无符号整数类型以避免符号扩展转换。
  • 根据读取和写入二进制数据时的建议,最好使用stream.readstream.write函数(它也可以通过块更好地读写)。
  • 如果您需要使用std::arraystd::vector来存储固定二进制数据,如果您需要从文件加载数据(std::vector是默认值)

固定代码:

#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]);
    }
}
相关问题