#include "stdafx.h"
#include<fstream>
struct A
{
string a;
string b;
int i;
};
int _tmain(int argc, _TCHAR* argv[])
{
A aa;
A b = {"don't worry","be happy",500};
ofstream out("seektest3.txt",ios::binary);
for (int i=0;i<5;i++)
{
out.seekp(i*sizeof(A));
out.write(reinterpret_cast<constchar *>(&b),sizeof(A));
cout << out.tellp()<<endl;
}
out.close();
ifstream in("seektest3.txt");
int i =0;
while (in && ! in.eof())
{
in.seekg(i * sizeof(A));
in.read(reinterpret_cast <char *>(&aa),sizeof(A));
cout << aa.a<< " "<<aa.b <<" "<<aa.i<<" "<< in.tellg()<<endl;
i++;
}
in.close();
getch();
return 0;
}
i just save a simple structure into a binary file and read it back immidiately. while writing and reading i mark each step of the proccess by outputting tellp and tellg.
And the output is surprising. Here it is:
68
136
204
272
340
don't worry be happy 500 68
don't worry be happy 500 136
don't worry be happy 500 204
don't worry be happy 500 272
don't worry be happy 500 340
don't worry be happy 500 -1
While saving it's OK. But look at the reading from file. The program reads it one excessive time and tellg gives me -1. But why? And what is more important how am i to avoid such a thing????
Thank you very much in advance. Any help is greatly appreciated.