简体   繁体   中英

Flatbuffers: write read binary file issue in c++?

My schema, encoder and decoder looks as below.

Schema :

namespace Myclient.sample;
table Person {
  age: short;
}
root_type Person;

Encoder:

int main(int argc, char *argv[])
{            
        flatbuffers::FlatBufferBuilder builder(1024);
        auto name = builder.CreateString("Mr Test");
        PersonBuilder mybuilder(builder);
        mybuilder.add_age(20);
        auto orc = mybuilder.Finish();
        builder.Finish(orc);
        uint8_t *buf = builder.GetBufferPointer();
        int size = builder.GetSize();
        ofstream wf(argv[1], ios::out | ios::binary);           
        wf.write((char*) &buf, size);   // overwrite
        wf.close();            
        return 0;
}

Decoder:

int main(int argc, char *argv[])
{
    //Read BIN file
    std::ifstream infile;
    infile.open(argv[1], std::ios::binary | std::ios:: in);
    infile.seekg(0, std::ios::end);
    int length = infile.tellg();
    infile.seekg(0, std::ios::beg);
    char *data = new char[length];
    infile.read(data, length);
    infile.close();

    flatbuffers::Verifier verifier(reinterpret_cast< unsigned char*> (data), length);
    bool ok = VerifyPersonBuffer(verifier);

    cout << "   verify value2: " << ok << endl;
    auto per = GetPerson(data);
    if (per)
    {
        cout << " person decoded" << endl;
        cout << "age is " << per->age() << endl;
    }
    return 0;
}

output of decoder: verify value2: 0 person decoded

Issue: could not decoded. is there any issue with biniary file read write, or schema definition. please help. Thanks.

wf.write((char*) &buf, size); will happily write the address of buf to that file followed by a large amount of garbage. The compiler was trying to warn you but you shut it up without reading the error. Change to buf and at least that problem is solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM