Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

writing structures using fstream in c++

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...