Read/Write struct containing string property to binary file

后端 未结 1 1692
情书的邮戳
情书的邮戳 2021-01-26 04:51

I am running in to an issue while reading/writing a struct having complex data specifically string. my struct looks like below.

struct MyRecord {
  char name[80]         


        
相关标签:
1条回答
  • 2021-01-26 05:39

    Add these two functions

    std::ostream & operator << ( std::ostream & os, const MyRecord & rec ) {
        os.write( rec.name, sizeof( rec.name ) );
        size_t sz = rec.location.size();
        os.write( & sz, iszeof( sz ) );
        os.write( rec.location.c_str(), sz );
        os.write( (char*) & balance, sizeof( rec.balance ) );
        os.write( (char*) & account_num, sizeof( rec.account_num ) );
        return os;
    }
    std::istream & operator >> ( std::ostream & is, MyRecord & rec ) {
        is.read( rec.name, sizeof( rec.name ) );
        size_t sz;
        is.read( & sz, iszeof( sz ) );
        rec.resize( sz );
        if ( sz != 0 ) {
            is.read( & rec.location[ 0 ], sz );
        }
        is.read( (char*) & balance, sizeof( rec.balance ) );
        is.read( (char*) & account_num, sizeof( rec.account_num ) );
    }
    

    And here is a usage

    ofstream outbal("balance", ios::out | ios::binary);
    outbal << acc;
    
    ifstream inbal("balance", ios::in | ios::binary);
    inbal >> acc;
    

    This is poor handmade similarity of Boost.Serialization. Indeed, it would be better to use boost, then my vehicle.

    0 讨论(0)
提交回复
热议问题