-
November 30th, 2008, 09:26 PM
#1
Read complex data from binary file
Here is the code I am trying to implement.
Code:
message *temp = new message;
myFile.seekg(ch);
myFile.read((char*)&temp, sizeof(message) ;
The problem is that for some reason the third line in this code is giving me problems and not returning a message at all even though I can verify that the message I am trying to read is in the file. Please let me know if you see something wrong. Thanks.
-
December 1st, 2008, 05:20 AM
#2
Re: Read complex data from binary file
You can't just write the entire instance into file and vice versa especially when the message class has member declared as pointers which you have to allocate and deallocate memory. So when you write the instance directly into the file, those pointer address will not make sense.
You should serialize your message instance into the file and deserialized from file into your message instance. IOW, you can provide a member function for writing the member variable one after another and another member function for reading the value for each member variable.
quoted from C++ Coding Standards:
KISS (Keep It Simple Software):
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
Avoid magic number:
Programming isn't magic, so don't incant it.
-
December 1st, 2008, 03:40 PM
#3
Re: Read complex data from binary file
Apart from what Kheun stated, your code has a bug, as temp is a pointer, so &temp is a pointer to pointer. So you are not reading in the data but the memory address where it is stored, which is unlikely to be stored to file.
More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf
Premature optimization is the root of all evil --Donald E. Knuth
Please read Information on posting before posting, especially the info on using [code] tags.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|