CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Nov 2008
    Posts
    20

    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.

  2. #2
    Join Date
    Oct 2002
    Location
    Singapore
    Posts
    3,128

    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.

  3. #3
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    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
  •  





Click Here to Expand Forum to Full Width

Featured