要求:
- 用fstream类创建并打开二进制文件
- 在文件中存入int,double 5 个基本数据类型
- 自定义类,并在文件中存入一个类对象
- 从文件中读取所有基本数据类型
- 从文件中读取第3个基本类型数据
- 从文件中读取类对象并使用
#include<iomanip> #include <fstream> #include<iostream> #include<cstring> using namespace std; class Time { public: int year; int month; void Display() { cout<<year<<" "<<month; } }; int main() { //用fstream创建并打开文件 fstream OutFile("binaryy.dat", ios::out| ios::in| ios::binary); //写入基本数据类型 int a;float b;double c;char d;bool e; a=1; b=1.34; c=1.3415826; d='p'; e=0; OutFile.write((char *)&a,sizeof(a)); OutFile.write((char *)&b,sizeof(b)); OutFile.write((char *)&c,sizeof(c)); OutFile.write((char *)&d,sizeof(d)); OutFile.write((char *)&e,sizeof(e)); //写入类对象 Time t; cin>>t.year>>t.month; OutFile.write((char *) &t, sizeof(t)); OutFile.close(); fstream inFile("binaryy.dat", ios::in | ios::binary); if (!inFile) { cout << "error" << endl; return 0; } //int a;float b;double c;char d;bool e; //读取所有基本类型 inFile.read((char *)&a,sizeof(a)); //cout<<a<<endl; inFile.read((char *)&b,sizeof(b)); //cout<<b<<endl; inFile.read((char *)&c,sizeof(c)); //cout<<c<<endl; inFile.read((char *)&d,sizeof(d)); //cout<<d<<endl; inFile.read((char *)&e,sizeof(e)); //cout<<e<<endl; cout<<a<<" "<<b<<" "<<c<<" "<<d<<" "<<e<<endl; //读取类对象 inFile.read((char *)&t,sizeof(t)); cout << t.year << " " << t.month << endl; //读取第三个基本类型 double tmp; inFile.seekg(sizeof(int)+sizeof(float),ios::beg); //while(inFile.get(tmp)) cout<<tmp; inFile.read((char *)&tmp,sizeof(double)); cout<<tmp<<endl; //使用类对象 t.Display(); inFile.close(); return 0; }
结果如下: