// Code derived from Stroustrup's PPP2 book// § 11.3.2 Binary files// -and beginning on p 391#include<fstream>#include<iostream>#include<stdexcept>#include<string>#include<vector>usingnamespacestd;voiderror(stringconst&s){throwruntime_error(s);}voiderror(stringconst&s1,stringconst&s2){error(s1+s2);}// needed for binary I/Otemplate<classT>char*as_bytes(T&i){void*addr=&i;// get the address of the first byte of memory used to// store the objectreturnstatic_cast<char*>(addr);// treat that memory as bytes}//------------------------------------------------------------------------------intmain()try{// open an istream for binary input from a file:cout<<"Please enter input file name\n";stringiname;cin>>iname;// binary tells the stream not to try anything clever with the bytesifstreamifs{iname,ios_base::binary};// note: stream mode is binaryif(!ifs)error("can't open input file ",iname);// open an ostream for binary output to a file:cout<<"Please enter output file name\n";stringoname;cin>>oname;// binary tells the stream not to try anything clever with the bytesofstreamofs{oname,ios_base::binary};// note: stream mode is binaryif(!ofs)error("can't open output file ",oname);// read from binary file:vector<int>v;for(intx;ifs.read(as_bytes(x),sizeof(int));)// note: reading bytesv.push_back(x);// . . . do something with v . . .// write to binary file:for(intx:v)ofs.write(as_bytes(x),sizeof(int));// note: writing bytes}catch(exceptionconst&e){cerr<<"error: "<<e.what()<<'\n';return1;}catch(...){cerr<<"Oops: unknown exception!\n";return2;}