《C++程序设计(第4版)》课本例题13.13

有5个学生的数据,要求:

1)把它们存到磁盘文件中;

2)将磁盘文件中的第1,3,5个学生数据读入程序,并显示出来;

3)将第3个学生的数据修改后存回磁盘文件中原有位置;

4)从磁盘文件读入修改后的5个学生数据并显示出来。

//例13.13  随机访问二进制数据文件
#include <iostream>
#include <fstream>
using namespace std;

struct student {
	int num;
	char name[20];
	float score;
};

int main() {
	student stud[5]{ 1001,"Li",85,
		1002,"Fang",97.5,
		1004,"Wang",54,
		1006,"Tan",76.5,
		1010,"ling",96 };
	fstream iofile("stud.dat", ios::in|ios::out|ios::binary);		//用 fstream 类建立输入输出二进制文件流对象 iofile
	if (!iofile) {
		cerr << "open error!\n";
		abort();				
	}
	iofile.write((char*)stud, sizeof(stud));			//for (int i = 0; i < 5; i++) iofile.write((char*)&stud[i], sizeof(stud[i]));
	student stud1[5]{};
	for (int i = 0; i < 5; 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],stud1[1],stud1[2]中
		cout << stud1[i / 2].num << ' ' << stud1[i / 2].name << ' ' << stud1[i / 2].score << endl;	//输出stud1中各成员的值
	}
	cout << endl;
	stud[2].num = 1012;		//修改第3个学生数据
	strcpy(stud[2].name, "Wu");
	stud[2].score = 60;
	iofile.seekp(2 * sizeof(stud[0]), ios::beg);		//定位于第3个学生数据的开头
	iofile.write((char*)&stud[2], sizeof(stud[2]));		//更新第3个学生数据
	iofile.seekg(0, ios::beg);							//重新定位于文件开头
	for (int i = 0; i < 5; i++) {
		iofile.read((char*)&stud[i], sizeof(stud[i]));
		cout << stud[i].num << ' ' << stud[i].name << ' ' << stud[i].score << endl;
	}
	iofile.close();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值