我正在阅读一个二进制文件,我知道它的结构,我试图放入一个结构但是当我来读取二进制文件时,我发现当它单独打印出结构时它似乎来了向右,但在第四次阅读时,它似乎将它添加到上一次阅读的最后一个成员。
这里的代码可能比我解释它更有意义:
STRUC
#pragma pack(push, r1, 1)
struct header
{
char headers[13];
unsigned int number;
char date[19];
char fws[16];
char collectversion[12];
unsigned int seiral;
char gain[12];
char padding[16];
};
主要
header head;
int index = 0;
fstream data;
data.open(argv[1], ios::in | ios::binary);
if(data.fail())
{
cout << "Unable to open the data file!!!" << endl;
cout << "It looks Like Someone Has Deleted the file!"<<endl<<endl<<endl;
return 0;
}
//check the size of head
cout << "Size:" << endl;
cout << sizeof(head) << endl;
data.seekg(0,std::ios::beg);
data.read( (char*)(&head.headers), sizeof(head.headers));
data.read( (char*)(&head.number), sizeof(head.number));
data.read( (char*)(&head.date), sizeof(head.date));
data.read( (char*)head.fws, sizeof(head.fws));
//Here im just testing to see if the correct data went in.
cout<<head.headers<< endl;
cout<<head.number<< endl;
cout<<head.date<< endl;
cout<<head.fws<< endl;
data.close();
return 0;
输出
Size:
96
CF001 D 01.00
0
15/11/2013 12:16:56CF10001001002000
CF10001001002000
由于某种原因fws似乎添加到head.date?但当我拿出线来读取head.fws我得到一个没有添加任何东西的日期?
我也知道要获取标题的更多数据,但我想检查数据,直到我写的是正确的
欢呼声
答案 0 :(得分:7)
1。您的日期声明为:
char date[19];
2。您的日期格式正好是19个字符:
15/11/2013 12:16:56
3。你以这种方式打印:
cout<<head.date
简而言之,您尝试使用其地址打印固定char[]
,这意味着它将被解释为 null-terminated c-string。它是否以空值终止?否。
要解决此问题,请将date
声明为:
char date[20];
填写后,添加空终止符:
date[19] = 0;
它适用于所有成员,将被解释为字符串文字。
答案 1 :(得分:2)
char date[19]
填充了15/11/2013 12:16:56
,这正好是19个有效字符。这没有为终止null留下空间,所以做cout&lt;&lt; head.date输出你的19个有效字符,然后输出一堆垃圾。