C++ 使用ifstream将二进制数据读入结构
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22192254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading binary data into struct with ifstream
提问by Dan
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:
具体来说,我试图用从文件中读取的数据填充这个“标题”结构:
struct Header {
char id[16];
int length;
int count;
};
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));
现在,如果我以这种方式读取文件,结果正是我想要的:
input.read((char*)&hdr, sizeof(hdr));
但是,如果我改为手动读取结构的每个变量,结果是乱码:
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?
我的问题是,这里发生了什么使这两种方法返回不同的结果?
采纳答案by Blaz Bratanic
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.
正如上面的评论所述,您可能缺少 hdr.length 和 hdr.count。我用 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;
}
回答by Marcel Zebrowski
It is also possible to read the struct in one step.
也可以一步读取结构体。
i.e. fh.read((char*)&h, sizeof(Header));
IE fh.read((char*)&h, sizeof(Header));