// Code derived from Stroustrup's PPP2 book// § 11.3.2 Binary files (v2)// -and beginning on p 391// note: this is an extended & reworked example of the book's original, that// demonstrates moving data for both the character & binary formats to/from disk// files, and confirming the resultant data are identical.#include<cstdlib>#include<fstream>#include<iomanip>#include<iostream>#include<vector>usingnamespacestd;// 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(){// comparison of some C++ built-in type sizes in bytes:cout<<"sizeof(char): \t\t"<<sizeof(char)<<'\n';cout<<"sizeof(int): \t\t"<<sizeof(int)<<'\n';cout<<"sizeof(double): \t"<<sizeof(double)<<"\n\n";//---// original source data vectorvector<int>constints{2147483647,-2147483648,2147483647,-2147483648,2147483647};// write the source data vector out to both text & binary -formatted files:ofstreamost_txt{"ints.txt"};// text data outputfor(autoi:ints)//ost_txt<<i<<'\n';// note: writing charsofstreamost_bin{"ints.bin",ios_base::binary};// binary data outputfor(autoi:ints)//ost_bin.write(as_bytes(i),sizeof(int));// note: writing bytesost_txt.close();// close both output file streams before proceedingost_bin.close();////---// read in binary data file:vector<int>b_ints;ifstreamist_bin{"ints.bin",ios_base::binary};// binary data input//for(intx;ist_bin.read(as_bytes(x),sizeof(int));)// note: reading bytesb_ints.push_back(x);//---// display the two vector's data for comparison:cout<<"source data (using C++ types):\n";for(autoi:ints)cout<<setw(12)<<i<<'\n';cout<<'\n';cout<<"reconstructed data (from binary file):\n";for(autoi:b_ints)cout<<setw(12)<<i<<'\n';cout<<'\n';cout<<" in-memory vector sizes match: "<<std::boolalpha<<(b_ints.size()==ints.size())<<"\n\n";//---// list the system disk file sizes for comparisonstd::system("ls -hl ints*");// note: clear diff in sizes for the same data}