//程序来源:http://c.biancheng.net/cpp/biancheng/view/260.html
#include <fstream>
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "io.h"
#include<iostream>
using namespace std;
struct student
{
int num;
char name[20];
float score;
};
int main()
{
student stud[5] = { 1001, "Li", 85, 1002, "Fun", 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!" << endl;
abort();
}
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 = i + 2)
{
iofile.seekg(i*sizeof(stud[i]), ios::beg); //定位于第,2,4学生数据开头,跳过了1 3 的若干字节
//先后读入个学生的数据,存放在stud1[0],stud[1]和stud[2]中
iofile.read((char *)&stud1[i / 2], sizeof(stud1[0]));
//输出stud1[0],stud[1]和stud[2]各成员的值
cout << i / 2 << endl;
cout << stud1[i / 2].num << " " << stud1[i / 2].name << " " << stud1[i / 2].score << endl;
}
cout << endl;
stud[2].num = 1012; //修改第个学生(序号为)的数据
strcpy(stud[2].name, "Wu");
stud[2].score = 60;
iofile.seekp(2 * sizeof(stud[0]), ios::beg); //定位于第个学生数据的开头
iofile.write((char *)&stud[2], sizeof(stud[2])); //更新第个学生数据
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;
}