Overwriting a record in a binary file

pangelll
pangelll used Ask the Experts™
on
Hi, here I am trying to overwrite a record in a binary file, however it overwrites the entire file with the write function.  I have attempted to use ios::trunc in the fstream constructor, but still produces same result.

*in this example code i'm simply trying to overwrite the first record, I can retrieve this.
fstream f("records.bin", ios::binary | ios::out);
 
f.seekp(0);
f.write(reinterpret_cast<const char*>(&binPerson),sizeof(binPerson));
f.close();

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2006
Commented:
IIRC this is issue with file opening mode ... You need to open it in rw mode ... opening in w mode truncates it

fstream f("records.bin", ios::binary | ios::out | ios::in);

Author

Commented:
wow! Thankyou.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial