首页 文章

cpp字节文件读取

提问于
浏览
0

我试图用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 回答

  • 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]);
        }
    }
    

相关问题