1/10/2017

Serialize/De-serialize data to a file using Flatbuffers


Read & Write

       

#include "flatbuffers/util.h"

flatbuffers::FlatBufferBuilder builder;

// Create something using builder
// ......

// Save to file
bool result = flatbuffers::SaveFile(filename.c_str(),
                                      (const char *) builder.GetBufferPointer(),
                                      (size_t) builder.GetSize(), true);

// Load from file
std::string buffer;
result = flatbuffers::LoadFile(fileName, true, &buffer);
printf("\nLoadFile Result = %d", result);


// You can write your own Save/load function
bool MySaveFile(const char *name, const char *buf, size_t len,
                     bool binary) {
  std::ofstream ofs(name, binary ? std::ofstream::binary : std::ofstream::out);
  if (!ofs.is_open()) return false;
  ofs.write(buf, len);
  return !ofs.bad();
}

bool MyLoadFileRaw(const char *name, bool binary, std::string *buf) {
  std::ifstream ifs(name, binary ? std::ifstream::binary : std::ifstream::in);
  if (!ifs.is_open()) {
    return false;
  }
  if (binary) {
    // The fastest way to read a file into a string.
    ifs.seekg(0, std::ios::end);
    auto size = ifs.tellg();
    (*buf).resize(static_cast(size));
    ifs.seekg(0, std::ios::beg);
    ifs.read(&(*buf)[0], (*buf).size());
  } else {
    // This is slower, but works correctly on all platforms for text files.
    std::ostringstream oss;
    oss << ifs.rdbuf();
    *buf = oss.str();
  }
  return !ifs.bad();
}
       
 


No comments:

Post a Comment