//将一批数据以二进制形式存放在磁盘文件中
#include<iostream>
#include<fstream>
using namespace std;
struct student
{
char name[20];
int num;
int age;
char sex;
};
int main()
{
student stud[3]={"Li",1001,18,'f',"Fun",1002,19,'m',"Wang",1004,17,'f'};
//定义输出文件流对象outfile,以输出方式打开二进制文件
ofstream outfile("stud.dat",ios::binary);
if(!outfile)
{
cout<<"open error!"<<endl;
abort(); //退出程序与exit(1)作用相同
}
for(int i=0;i<3;i++)
//第一个形参要用(char *)进行强制转换为字符指针
//第二个形参是指定一次输出的字节数
outfile.write(( char *)&stud[i],sizeof(stud[i]));
outfile.close(); //关闭文件
system("pause");
return 0;
}
//将刚才以二进制形式存放在磁盘文件的数据读入内存并在显示器上显示
#include<iostream>
#include<fstream>
using namespace std;
struct student
{
char name[20];
int num;
int age;
char sex;
};
int main()
{
student stud[3];
int i;
//定义输入文件流对象infile,以输入方式打开磁盘文件stud.dat
ifstream infile("stud.dat",ios::binary);
if(!infile) //打开失败
{
cerr<<"open error!"<<endl;
abort();
}
for(i=0;i<3;i++)
//调用成员函数read来读二进制文件
infile.read((char *)&stud[i],sizeof(stud[i]));
infile.close(); //关闭文件
for(i=0;i<3;i++) //分别输出三个同学的信息
{
cout<<"NO."<<i+1<<endl;
cout<<"name:"<<stud[i].name<<endl;
cout<<"num:"<<stud[i].num<<endl;
cout<<"age:"<<stud[i].age<<endl;
cout<<"sex:"<<stud[i].sex<<endl;
cout<<endl;
}
system("pause");
return 0;
}