读二进制数据与ifstream的结构 [英] Reading binary data into struct with ifstream
问题描述
我想用ifstream的从文件中读取二进制数据。
具体来说,我想填充从文件中读取数据的这个头结构:
结构头{
焦炭ID [16];
INT长;
诠释计数;
};
-
现在,如果我用这种方式读取文件,结果是正是我想要的:
input.read((字符*)及HDR,sizeof的(HDR));
-
但是,如果我不是手动读取结构的每个变量,结果是乱码:
input.read((字符*)及hdr.id,sizeof的(hdr.id));
input.read((字符*)及hdr.length,sizeof的(hdr.length));
input.read((字符*)及hdr.count,sizeof的(hdr.count));
我的问题是,这里发生了什么,使得这两种方法返回不同的结果?
如上国的意见,你可能缺少hdr.length和hdr.count。
我用gcc 4.8试了一下,铛3.5和它工作正常。
的#include<&iostream的GT;
#包括LT&;&的fstream GT;的#pragma包(推,R1,1)
结构头{
焦炭ID [15];
INT长;
诠释计数;
};
的#pragma包(POP,R 1)诠释主(){
首标h = {alalalala,5,10}; 的std :: fstream的FH;
fh.open(test.txt的性病:: fstream的::出来|的std :: fstream的二进制::);
fh.write((字符*)及H,的sizeof(头));
fh.close(); fh.open(test.txt的的std :: fstream的::在|的std :: fstream的二进制::); fh.read((字符*)及h.id,sizeof的(h.id));
fh.read((字符*)及h.length,sizeof的(h.length));
fh.read((字符*)及h.count,sizeof的(h.count)); fh.close(); 性病::法院LT&;< h.id<< << h.length<< << h.count<<的std :: ENDL;
}
I'm trying to read binary data from a file using 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));
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. 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的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!