Hey guys, I am using g++ to compile my c++ projects and i noticed that the code is not giving the correct output. The last data written in the file is output twice. My c++ version is 4.1.2 I used the command
g++ -o test test.cpp
I have tried creating textfiles with fstream; they worked perfect.
Here is the code:
//test.cpp
#include<iostream>
#include<fstream>
using namespace std;
class a1{int i,j;
public:
void getdat()
{
cin>>i>>j; //input 2 test variables
}
void putdata()
{
cout<<i<<j;
}
}a;
int main(int argc, char *argv[])
{
fstream f("abc.dat",ios::binary|ios:
ut|ios::app);
int i;
for(i=0;i<2;i++) //input 2 test objects
{a.getdat();
f.write((char*)&a,sizeof(a));
}
f.close();
f.open("abc.dat",ios::binary|ios::in);
int w=0;
while(f)
{
f.read((char*)&a,sizeof(a));
w++;
//a.putdata();
}
f.seekg(0);
for(i=0;i<w;i++)
{
f.read((char*)&a,sizeof(a));
a.putdata();
}
f.close();
return 0;
}