ang*_*ins 0 c++ binary alignment
我正在阅读一个二进制文件,我知道它的结构,我试图放入一个结构但是当我来读取二进制文件时,我发现当它单独打印出结构时,它似乎正确但是然后在第四次阅读时,它似乎将它添加到上次读取的最后一个成员.
这里的代码可能比我解释它更有意义:
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];
};
Run Code Online (Sandbox Code Playgroud)
主要
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;
Run Code Online (Sandbox Code Playgroud)
产量
Size:
96
CF001 D 01.00
0
15/11/2013 12:16:56CF10001001002000
CF10001001002000
Run Code Online (Sandbox Code Playgroud)
由于某种原因,fws似乎增加了head.date?但当我拿出线来阅读head.fws我得到一个没有添加任何东西的日期?
我也知道更多的数据来获取标题,但我想检查数据,直到我写的是正确的
干杯
1.你的约会被声明为:
char date[19];
Run Code Online (Sandbox Code Playgroud)
2.您的日期格式正好是19个字符:
15/11/2013 12:16:56
Run Code Online (Sandbox Code Playgroud)
3.你打印这种方式:
cout<<head.date
Run Code Online (Sandbox Code Playgroud)
简而言之,您尝试char[]使用其地址进行固定打印,这意味着它将被解释为以null结尾的 c-string.它是否以空值终止?没有.
要解决此问题,请声明date为:
char date[20];
Run Code Online (Sandbox Code Playgroud)
在填充之后,追加null终止符:
date[19] = 0;
Run Code Online (Sandbox Code Playgroud)
它适用于所有成员,将被解释为字符串文字.