#include <fstream>
#include<iostream>
using namespace std;
struct Student // 学生结构
{
int num; // 学号
char name[16]; // 姓名
float score1;
float score2;
float score3; // 成绩
};
int main(void) // 主函数main()
{
#pragma region (0)将它们存储在磁盘文件中;
Student stu[3] = { {2009101, "李靖", 98,89,56}, {2009102, "刘敏", 100,23,25},{2009103, "王强", 99,56,89} }; // 定义数组
fstream f("stu.dat", ios::out | ios::binary);// 定义文件对象,这样如果文件不存储将建立一个空文件
if (f.fail()) // 打开文件失败
{
cout << "打开文件失败!" << endl;
exit(1); // 退出程序
}
for (int i = 0; i < 3; i++)
f.write((char *)&stu[i], sizeof(stu));// 写数据到文件中
f.seekp(0 * sizeof(Student), ios::beg); // 定位于第1个学生数据的起始位置
for (int i = 0; i < 3; i++)
{
cout << stu[i].name << " " << stu[i].name << " " << stu[i].score1 << " " << stu[i].score2 << " " << stu[i].score3
<< endl; // 显示学生信息
}
system("pause");
cout << endl;
f.close();// 关闭文件
为什么从记事本打开就是乱码啊,notepad也是。