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

后端 未结 3 2048
囚心锁ツ
囚心锁ツ 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:38

    It's not easy to reproduce the error, due to your large source code and missing data file. But a quick inspection shows that you read and write the binary data using bloc operations:

        Triangle trig; 
        ...
        File.read((char*)&trig, sizeof(Triangle));
    

    Unfortunately this kind of approach only works if the object you want to save/load is of a class that is trivially copyable, as the following code will demonstrate:

    if (is_trivially_copyable::value) 
        cout << "Triangle is  trivially copyable" << endl; 
    else cout << "Triangle is not trivially copyable" << endl; 
    

    So you'll have to serialize the object content writing field by field instead of using a bloc operation. This FAQ on serialization should help you to consider the alternatives.

提交回复
热议问题