使用 ifstream 将二进制数据读入结构

Reading binary data into struct with ifstream(使用 ifstream 将二进制数据读入结构)

本文介绍了使用 ifstream 将二进制数据读入结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 ifstream 从文件中读取二进制数据.

I'm trying to read binary data from a file using ifstream.

具体来说,我正在尝试用从文件中读取的数据填充这个Header"结构:

Specifically, I'm trying to populate this "Header" struct with data read from a file:

struct Header {
    char id[16];
    int length;
    int count;
};

  1. 现在,如果我以这种方式读取文件,结果正是我想要的:

  1. Now, if I read the file in this way, the result is exactly what I want:

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

  • 但如果我改为手动读取结构的每个变量,结果就会乱码:

  • 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?

    推荐答案

    正如上面的评论所说,您可能缺少 hdr.length 和 hdr.count.我用 gcc 4.8 和 clang 3.5 试了一下,它工作正常.

    As the comment above states, you are probably missing hdr.length and hdr.count. I tried it with gcc 4.8 and clang 3.5 and it works correctly.

    #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;
    }
    

    这篇关于使用 ifstream 将二进制数据读入结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

    本文标题为:使用 ifstream 将二进制数据读入结构

    基础教程推荐