question about file proccessing

Hi guys. Can anyone explain me this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#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<const char *>(&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.
Last edited on
Topic archived. No new replies allowed.