类型:转载 责任编辑:asp.net 日期:2007/05/23
热门软件下载:
#include <iostream.h>
#include <fstream.h>
struct stu
{
int age;
char fname[10];
char sname[10];
int sex;
}student,student1;
main()
{
cout<<endl<<"size of stu:"<<sizeof student<<endl;
ofstream out("1.txt",ios::out);
if(!out)
cout<<\n<<"open file failure!"<<endl;
while(cin>>student.age>>student.fname>>student.sname>>student.sex)
{
out.write(reinterpret_cast<const char *>(&student),sizeof(student));
}
ifstream in("1.txt");
if(!in)
cout<<\n<<"open file failure!"<<endl;
in.read(reinterpret_cast<char *>(&student1),sizeof(student1));
cout<<"student1:"<<endl;
cout<<"age: "<<student1.age<<endl;
cout<<"fname: "<<student1.fname<<endl;
cout<<"sname: "<<student1.sname<<endl;
cout<<"sex: "<<student1.sex<<endl;
}
程序如上所示,执行out.write后,1.txt文件里面,整形的数显示为,字符数组可以显示,但是后面
执行读操作,结果什么都没有!
问题1. 为什么in.read读不出结果?
问题2. 结构体里面的成员变量具体怎么分配空间,以前有人说4个字节对齐,
那么age -4b,fname=12(本来10b,因为按字对齐),sname=12b(同前),sex-4b
一共32个阿,怎么我用sizeof(stu)显示28个?有人说中间的两个字符数组在一起20,
具体怎么解释呢?
网友回答: