现在的位置: 首页 > 综合 > 正文

第十七周任务0

2013年09月11日 ⁄ 综合 ⁄ 共 2033字 ⁄ 字号 评论关闭

阅读程序指出功能:

#include<iostream>
#include <fstream>
using namespace std;

class Student//定义Student类
{
public:
	Student(void){}
	Student(int n, char nam[20], float s):num(n),score(s){strcpy(name,nam);}//字符串复制
	void setNum(int n){num=n;}
	void setName(char nam[20]){strcpy(name,nam);}
	void setScore(float s){score=s;}
	void show() {cout<<num<<" "<<name<<" "<<score<<endl;} //显示通过<<的重载实现更自然
private:
	int num;
	char name[20];
	float score;
};
int main( )
{ 
	Student stud[5]={
		Student(1001,"Li",85),
		Student(1002,"Fun",97.5),
		Student(1004,"Wang",54),
		Student(1006,"Tan",76.5),
		Student(1010,"ling",96)
	};
	fstream iofile("stud.dat",ios::in|ios::out|ios::binary);//用fstream类定义输入输出二进制文件流对象iofile
	if(!iofile)
	{ 
		cerr<<"open error!"<<endl;
		abort( );//退出程序
	}
	cout<<"(1)向磁盘文件输出个学生的数据并显示出来"<<endl;
	for(int i=0;i<5;i++)
	{
		iofile.write((char *)&stud[i],sizeof(stud[i]));//将数据写入文件
		stud[i].show();//显示当前对象的数据
	}
	cout<<"(2)将磁盘文件中的第,3,5个学生数据读入程序,并显示出来"<<endl;
	Student stud1[5];//用来存放从磁盘文件读入的数据
	for(int i=0;i<5;i=i+2)
	{ 
		iofile.seekg(i*sizeof(stud[i]),ios::beg);//定位于第0,2,4学生数据开头
		iofile.read((char *)&stud1[i/2],sizeof(stud1[0]));
		//先后读入3个学生的数据,存放在stud1[0],stud[1],stud[2]中
		stud1[i/2].show();
	}
	cout<<endl;
	cout<<"(3)将第个学生的数据修改后存回磁盘文件中的原有位置"<<endl;
	stud[2].setNum(1012);//修改第3个学生的数据
	stud[2].setName("Wu");
	stud[2].setScore(60);
	iofile.seekp(2*sizeof(stud[0]),ios::beg);//定位于第3个学生数据的开头
	iofile.write((char *)&stud[2],sizeof(stud[2]));//更新第3个学生的数据
	iofile.seekg(0,ios::beg);//重新定位于文件开头
	cout<<"(4)从磁盘文件读入修改后的个学生的数据并显示出来"<<endl;
	for(int i=0;i<5;i++)
	{ iofile.read((char *)&stud[i],sizeof(stud[i]));//读入五个学生的数据
	stud[i].show();
	}
	iofile.close( );
	system("pause");
	return 0;
}

运行结果;

(1)向磁盘文件输出个学生的数据并显示出来
1001 Li 85
1002 Fun 97.5
1004 Wang 54
1006 Tan 76.5
1010 ling 96
(2)将磁盘文件中的第,3,5个学生数据读入程序,并显示出来
1001 Li 85
1004 Wang 54
1010 ling 96

(3)将第个学生的数据修改后存回磁盘文件中的原有位置
(4)从磁盘文件读入修改后的个学生的数据并显示出来
1001 Li 85
1002 Fun 97.5
1012 Wu 60
1006 Tan 76.5
1010 ling 96
请按任意键继续. . .

不能用ifstream,ofstream类定义输入输出的二进制文件流对象,而应当用fstream类

文件流与文件指针有关的成员函数
           成员函数                       作用
gcount()
tellg()
seekg(文件中的位置)
seekg(位移量,参照位置)
tellp()
seekp(文件中的位置)
seekp(位移量,参照位置)
返回最后一次输入所读入的字节数
返回输入文件指针的当前位置
将输入文件中指针移到指定的位置
以参照位置为基础移动若干字节
返回输出文件指针当前的位置
将输出文件中指针移到指定的位置
以参照位置为基础移动若干字节

抱歉!评论已关闭.