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?

Recommended Answers

All 3 Replies

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.

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
}

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..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.