I have a binary file that contains the data that I want to load into a Flatbuffer object. Just as a toy example, I'm using the following schema:
namespace SingleInt;
table Single{
value:uint32;
}
root_type Single;
Consider that my binary file contains exactly this information: an unsigned int
value, and nothing else. In this case, I stored the value 5
on my file. I'm trying to assign and display the content of my binary file into my Flatbuffer object by using the following method:
void readFbs(){
int fd = open("myfile", O_RDONLY, 0);
unsigned int* memmap = (unsigned int*)mmap(0, sizeof(unsigned int), PROT_READ, MAP_SHARED, fd, 0);
auto myfile = SingleInt::GetSingle(memmap);
std::cout<<myfile->value()<<std::endl;
}
The output is the value 0
, instead of the value 5
that I thought I'd get.
My question is: knowing how a binary file was serialized and written, if I create a schema that represents it, is it possible to load its content into a Flatbuffer object?
Edit: function to write data
void writebin(){
unsigned int var = 5;
std::ofstream OutFile;
OutFile.open("myfile", std::ios::out | std::ios::binary);
OutFile.write(reinterpret_cast<char*>(&var), sizeof(var));
OutFile.close();
}
Your writing code just writes a naked int
to a file. You need to instead use the FlatBuffers functions to write something that is compatible with the FlatBuffers format, e.g.
FlatBufferBuilder fbb;
fbb.Finish(CreateSingle(fbb, 5));
// Now write the buffer starting at fbb.GetBufferPointer() for fbb.GetSize() to a file.
More details at https://google.github.io/flatbuffers/flatbuffers_guide_tutorial.html