Reading/writing files to/from a struct/class

前端 未结 2 1639
死守一世寂寞
死守一世寂寞 2021-01-16 05:52

I\'d like to read a file into a struct or class, but after some reading i\'ve gathered that its not a good idea to do something like:

int MyClass::loadFile(          


        
2条回答
  •  天命终不由人
    2021-01-16 06:20

    The answer is : there is no silver bullet to this problem.

    One way you can eliminate the padding to ensure that the data members in your class is to use(in MSVC which you are using)

    #pragma pack( push, 1 )
    
    class YourClass {
        // your data members here
        int Data1;
        char Data2;
        // etc...
    };
    
    #pragma pack( pop )
    

    The main usefulness of this approach is if your class matches a predefined format such as a bitmap header. If it is a general purpose class to represent a cat, dog, whatever then dont use this approach. Other thing if doing this is to make sure you know the length in bytes of the data types for your compiler, if your code is EVER going to be multi platform then you should use explicit sizes for the members such as __int32 etc.

    If this is a general class, then in your save member, each value should be written explicitly. A tip to do this is to create or get from sourceforge or somewhere good code to help do this. Ideally, some code that allows the member to be named, I use something similar to :

    SET_WRITE_DOUBLE( L"NameOfThing", DoubleMemberOfClass );
    SET_WRITE_INT( L"NameOfThing2", IntMemberOfClass );
    // and so on...
    

    I created the code behind these macros, which I am not sharing for now but a clever person can create their own code to save named to stream in an unordered-set. This I have found is the perfect approach because if you add or subtract data members to your class, the save/load is not dependent on the binary representation and order of your save, as your class will doubtless evolve through time if you save sequentially this is a problem you will face.

    I hope this helps.

提交回复
热议问题