I have created a class which has two string objects. This class writes and reads the two string objects to/from a file in Binary Mode. All this is defined in the header file "a_details.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class AVENGERS{
public:
string codename;
string realname;
const size_t JUMP = 2*sizeof(string);
AVENGERS(string code=" ",string real=" "){codename=code;realname=real;}
void read(istream & is){
is.read((char*)&codename,sizeof(string));
is.read((char*)&realname,sizeof(string));
}
void write(ostream & os){
os.write((char*)&codename,sizeof(string));
os.write((char*)&realname,sizeof(string));
}
};
istream & operator >> (istream & is,AVENGERS & A)
{
is>>A.codename>>A.realname;
return is;
}
ostream & operator << (ostream & os,AVENGERS & A)
{
os<<A.codename<<"-"<<A.realname;
return os;
}
below is the file "a_write.cpp "which opens a file in binary mode and writes 3 AVENGERS objects(and hence, 6 strings).
#include <iostream>
#include <fstream>
#include <string>
#include "a_details.h"
using namespace std;
int main(){
fstream ffile("avengers.bin", ios_base::binary | ios_base::in |ios_base::out);
if(ffile.is_open()){
AVENGERS("Iron Man","Tony Stark").write(ffile);
AVENGERS("Captain America","Steve Rogers").write(ffile);
AVENGERS("Hulk","Bruce Banner").write(ffile);
cout<<"writing done\n";
ffile.close();
}
}
After that, i checked the size of avengers.bin to be 24 bytes to verify if writing operation was done properly. But then , when i create another file "a_read.cpp" to read in the data, it gives me errors. below is the code.
#include <iostream>
#include <fstream>
#include <string>
#include "a_details.h"
using namespace std;
int main(){
fstream ffile("avengers.bin" , ios_base::binary | ios_base :: in |ios_base::out);
if(ffile.is_open()){
cout<<"file is going to open"<<endl;
while(!ffile.eof())
{
cout<<"entered loop\n";
AVENGERS TEMPO(" "," ");
TEMPO.read(ffile);
cout<<"read data\n";
if(ffile.gcount()==0)break;
cout<<"this means file is not at end of file\n";
}
cout<<"this means file is at end of file\n";
ffile.close();
}
cout<<"reading done";
return 0;
}
The cout statements in between are for my reference,since i wanted to check where was the problem. But i am unable to understand. The program loops 1 time, then crashes. Can somebody please help me? This is the Error message