c++ Read/Write class from/to binary file

后端 未结 3 2052
囚心锁ツ
囚心锁ツ 2020-12-03 23:07

I need to write a class to a binary file, and then I need to read it back.

I have Triangle and BinaryFile classes, and some other classes.

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 23:47

    What you are looking for is to serialize your classes/data that should be saved to file. There are several libraries that has been optimized regarding time and memory consumption for this. Would you mind using a 3rd party library?

    If not, have a look at for example boost serialization, cereal or maybe even Google's ProtoBuf. I recon Cereal is a good start if you are using C++11.

    If you'd like to write your own serialization you'd have to consider that for every object that has a dynamic size (such as a string), you will also need to save the object's size to the file. For more info please have a look here:

    https://stackoverflow.com/a/11003590/5874704

提交回复
热议问题