0

Hello.

I have a program that reads from file, modifies its content and saves. But there's a problem - when i write only one block of data, two of them are been written!

class person
{ ... };

...
person User;
fstream File;
File.open("file.dtb", ios::in|ios::out|ios::binary);
	
// Adding 1 record:
File.seekp(number, ios::end);
File.write((char*)&User,sizeof(person));
number=1;

// Adding second record(same as 1st):
File.seekp(number*sizeof(person), ios::beg);
File.write((char*)&User,sizeof(person));	

"User"'s data changed...

//Changing the 1st record:
number=0;
File.seekp(number*sizeof(person), ios::beg);
File.write((char*)&User,sizeof(person));

But after that

// it reads changed record once, and first record - twice.
// 3 entries instead on 2.
while(!File.eof())
{
	File.read((char*)&User, sizeof(person));
	User.dispdata();
	cout << endl;
}

How to fix this, so it will output initial data and changed data only once?

Edited by overpower8: n/a

3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by overpower8
0

It would be most helpful to have a minimal piece of code which builds and demonstrates the unwanted behavior. Otherwise we can only guess.
Usually you need to flush the stream between writes and reads.

0

line 29 is wrong. eof() doesn't work that way.

file.seekp(0, ios::begin); // start at beginning of file
while( File.read((char*)&User, sizeof(person)))
{
     // blabla
}

Edited by Ancient Dragon: n/a

0

line 29 is wrong. eof() doesn't work that way.

file.seekp(0, ios::begin); // start at beginning of file
while( File.read((char*)&User, sizeof(person)))
{
     // blabla
}

Thanks 4 the reply. I'll try this method..

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.