Requirements:
- To create and open a binary file with the FStream class
- Deposit Int,double 5 Basic data types in a file
- Custom classes and store a class object in the file
- Read all basic data types from a file
- Reading the 3rd basic type data from a file
- Reads the class object from the file and uses the
1#include <iomanip>2#include <fstream>3#include <iostream>4#include <cstring>5 using namespacestd;6 classTime {7 Public:8 intYear ;9 intmonth;Ten voidDisplay () One { Acout<<year<<" "<<month; - } - }; the intMain () - { - //Create and open a file with FStream -FStream OutFile ("Binaryy.dat"Ios:: out| Ios::inch|ios::binary); + //write basic data type - intAfloatbDoubleCCharDBOOLe; +A=1; b=1.34; C=1.3415826; D='P'; E=0; AOutfile.write ((Char*) &a,sizeof(a)); atOutfile.write ((Char*) &b,sizeof(b)); -Outfile.write ((Char*) &c,sizeof(c)); -Outfile.write ((Char*) &d,sizeof(d)); -Outfile.write ((Char*) &e,sizeof(e)); - //Write Class object - Time t; inCin>>t.year>>T.month; -Outfile.write ((Char*) &t,sizeof(t)); to outfile.close (); +FStream InFile ("Binaryy.dat"Ios::inch|ios::binary); - if(!inFile) the { *cout <<"Error"<<Endl; $ return 0;Panax Notoginseng } - //int a;float b;double C;char d;bool e; the //Read all basic types +Infile.read ((Char*) &a,sizeof(a)); A //cout<<a<<endl; theInfile.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)); the //cout<<e<<endl; -cout<<a<<" "<<b<<" "<<c<<" "<<d<<" "<<e<<Endl;Wuyi //Read Class object theInfile.read ((Char*) &t,sizeof(t)); -cout << t.year <<" "<< T.month <<Endl; Wu //read the third basic type - Doubletmp; AboutINFILE.SEEKG (sizeof(int)+sizeof(float), Ios::beg); $ //While (Infile.get (TMP)) cout<<tmp; -Infile.read ((Char*) &tmp,sizeof(Double)); -cout<<tmp<<Endl; - //working with class objects A T.display (); + infile.close (); the return 0; -}
The results are as follows:
C + + binary file read and write