[ create a new paste ] login | about

Project: chehob
Link: http://chehob.codepad.org/B1W4lLRF    [ raw code | fork ]

chehob - C++, pasted on Aug 7:
#ifndef SERIALIZATION_H
#define SERIALIZATION_H

namespace Serialization
{
  namespace Binary
  {
    // Writing

    // Generic write method
    // Writes basic type data to file
    template <typename T>
    void Write(std::fstream& fs, T data)
    {
      fs.write(reinterpret_cast<char*>(&data), sizeof(T));
    }

    // std::string write method
    // Writes C++ string to file
    void Write(std::fstream& fs, const std::string& str)
    {
      int size = static_cast<int>(str.size());
      Write(fs, size);                          // Write string size. Generic Write()
      fs.write(str.c_str(), size);              // Write string data
    }

    // Reading

    // Generic read method
    // Reads basic type data from file
    template <typename T>
    void Read(std::fstream& fs, T& data)
    {
      fs.read(reinterpret_cast<char*>(&data), sizeof(T));
    }

    // std::string read method
    // Reads C++ string from file
    void Read(std::fstream& fs, std::string& str)
    {
      int size;
      Read(fs, size);                           // Get string size. Generic Read()
      char* buffer = new char[size+1];          // Allocate char buffer
      fs.read( buffer, size );                  // Read string data to buffer
      buffer[size] = 0;                         // Set '/0' terminating character
      str = buffer;                             // Load string with data
      delete [] buffer;
    }
  }
}

#endif


Create a new paste based on this one


Comments: