简体   繁体   English

使用ifstream将二进制数据读入struct

[英]Reading binary data into struct with ifstream

I'm trying to read binary data from a file using ifstream. 我正在尝试使用ifstream从文件中读取二进制数据。

Specifically, I'm trying to populate this "Header" struct with data read from a file: 具体来说,我正在尝试使用从文件读取的数据填充此“Header”结构:

struct Header {
    char id[16];
    int length;
    int count;
};
  1. Now, if I read the file in this way, the result is exactly what I want: 现在,如果我以这种方式读取文件,结果正是我想要的:

     input.read((char*)&hdr, sizeof(hdr)); 
  2. But if I instead read each variable of the struct manually, the results are gibberish: 但是,如果我手动读取结构的每个变量,结果是乱码:

     input.read((char*)&hdr.id, sizeof(hdr.id)); input.read((char*)&hdr.length, sizeof(hdr.length)); input.read((char*)&hdr.count, sizeof(hdr.count)); 

My question is, what is happening here that makes these two methods return different results? 我的问题是,这里发生了什么使这两种方法返回不同的结果?

As the comment above states, you are probably missing hdr.length and hdr.count. 正如上面的评论所述,您可能缺少hdr.length和hdr.count。 I tried it with gcc 4.8 and clang 3.5 and it works correctly. 我尝试使用gcc 4.8和clang 3.5并且它可以正常工作。

#include <iostream>
#include <fstream>

#pragma pack(push, r1, 1)
struct Header {
    char id[15];
    int length;
    int count;
};
#pragma pack(pop, r1)

int main() {
  Header h = {"alalalala", 5, 10};

  std::fstream fh;
  fh.open("test.txt", std::fstream::out | std::fstream::binary);
  fh.write((char*)&h, sizeof(Header));
  fh.close();

  fh.open("test.txt", std::fstream::in | std::fstream::binary);

  fh.read((char*)&h.id, sizeof(h.id));
  fh.read((char*)&h.length, sizeof(h.length));
  fh.read((char*)&h.count, sizeof(h.count));

  fh.close();

  std::cout << h.id << " " << h.length << " " << h.count << std::endl;
}

It is also possible to read the struct in one step. 也可以一步读取结构。

ie fh.read((char*)&h, sizeof(Header)); fh.read((char*)&h, sizeof(Header));

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

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