您的位置:首页 > 编程语言 > C语言/C++

对二进制文件的操作(c++ 程序设计 by 谭浩强 课本实例)

2011-11-27 20:21 357 查看
//将一批数据以二进制形式存放在磁盘文件中
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: