-2

Please tell me that the following line writes the address of the structure variable to the file or it writes the values of members of the structure.

 file_write.write((char*)&structure_data,sizeOfStructure);

Where file_write is fstream's object and "structure_data" is a struct having 3 members of integer datatypes. Thanks.

8
  • 3
    It takes whatever structure_data is, and just copies those blob of bytes to a file. It doesn't figure out what the members are. Also, this is the cause for thousands of SO questions that erroneously do codiing like this, where structure_data cannot be written to a file this way and have the file make sense. Look up object serialization. Commented Jan 29, 2018 at 17:35
  • 1
    it is not writing the address, its writing the data in the structure. Now depending on the struct that might not do what you expect Commented Jan 29, 2018 at 17:37
  • write also takes a char*, so you are converting to char* here, which IIRC results in implementation-defined behavior. Commented Jan 29, 2018 at 17:39
  • Please suggest me an effective alternative for above line.@PaulMcKenzie Commented Jan 29, 2018 at 17:43
  • @Ehtesham See the answer I gave. The easiest thing is to write each member to the file using the operator << for each item. Commented Jan 29, 2018 at 17:47

1 Answer 1

4

This line:

file_write.write((char*)&structure_data,sizeOfStructure);

takes whatever structure_data is, and just copies those blob of bytes that makes up structure_data to a file.

It doesn't figure out what the members are. Also, this is the cause for thousands of SO questions that erroneously do coding like this, where structure_data cannot be written to a file this way and have the file contents make sense. It is quickly discovered that the contents of the file are useless when an attempt to read back the data into a program is unsuccessful.

Most of the time in those scenarios structure_data would contain pointers, or members that are not C-layout compatible, i.e. non-POD types such as std::string or std::vector, that basically renders this technique of writing to a file like this totally useless (and invalid).

Look up object serialization such as this link on the topic

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.