I wrote some piece of code which reads and write multiple data structures on a file using C++. I would be grateful to get your feedback on what you think about the code (it works at least when I tested). Thanks.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
// data structure to be written to a file
struct WebSites
{
char SiteName[100];
int Rank;
}s1,s2,s3,s4;
int _tmain(int argc, _TCHAR* argv[])
{
strcpy(s1.SiteName, "www.ppp.com");
s1.Rank = 0;
strcpy(s2.SiteName, "www.rrr.com");
s2.Rank = 111;
strcpy(s3.SiteName, "www.code.com");
s3.Rank = 123;
strcpy(s4.SiteName, "www.yahoo.com");
s4.Rank = 14;
// write
fstream binary_file("c:\\test.dat",ios::out|ios::binary|ios::app);
binary_file.write(reinterpret_cast<char *>(&s1),sizeof(WebSites));
binary_file.write(reinterpret_cast<char *>(&s2),sizeof(WebSites));
binary_file.write(reinterpret_cast<char *>(&s3),sizeof(WebSites));
binary_file.write(reinterpret_cast<char *>(&s4),sizeof(WebSites));
binary_file.close();
// Read data
fstream binary_file2("c:\\test.dat",ios::binary|ios::in| ios::ate );
int size = binary_file2.tellg();
for(int i = 0; i<size/sizeof(WebSites); i++)
{
WebSites p_Data;
binary_file2.seekg(i*sizeof(WebSites));
binary_file2.read(reinterpret_cast<char *>(&p_Data),sizeof(WebSites));
cout<<p_Data.SiteName<<endl;
cout<<"Rank: "<< p_Data.Rank<<endl;
}
binary_file2.close();
return 0;
}