自考新教材-p316

源程序:

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
class CStudent
{
public:
char id[11]; //学号

char name[21]; //姓名

int score; //成绩
};
int main()
{
CStudent stu;
int count = 0, nbyte = 0;
ifstream inFile("c:\tmp\students.dat", ios::in | ios::binary);//以二进制读方式打开
if (!inFile) //条件成立,则说明文件打开错误
{
cout << "创建文件失败" << endl;
return 0;
}
cout << "学生学号 姓名 成绩 ";

while (inFile.read((char*)&stu, sizeof(stu))) //读取记录直到文件结束
{
cout << left << setw(10) << stu.id << " " << setw(20) << stu.name
<< " " << setw(3) << right << stu.score << endl;
count++;
nbyte += inFile.gcount(); //得到本次read读取的字节数量
}
cout << "共有记录数:" << count << ",字节数:" << nbyte << endl;
inFile.close();
system("pause");
return 0;
}

运行结果:

原文地址:https://www.cnblogs.com/duanqibo/p/12263474.html