Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


How to Create Persistent Objects-2 : Page 2




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Step 1: Serializing Built-in Datatypes
Ultimately, every object consists of built-in data members such as int, bool, char [] and so on. Our first exercise is to write such datatypes to an ofstream (read more on <fstream> file I/O here). We store the values in their binary format. For this purpose, we use the write() and read() member functions. write() takes the address and the size of a variable and writes its bit pattern to a file stream. read() takes two arguments of type char * and long which contain buffer's address and its size in bytes, respectively. The following example demonstrates how to store two integers in an ofstream:

#include <:fstream>: using namespace std; int main() { int x,y; //mouse coordinates //..assign values to x and y ofstream archive("coord.dat", ios::binary); archive.write(reinterpret_cast(&x), sizeof (x)); archive.write(reinterpret_cast(&x), sizeof (x)); archive.close(); }

The use of reinterpret_cast is necessary because write() takes const char * as its first argument whereas &x and &y are of type int *.

We retrieve the previously stored values as follows:

#include <fstream> using namespace std; int main() { int x,y; ifstream archive("coord.dat"); archive.read((reinterpret_cast(&x), sizeof(x)); archive.read((reinterpret_cast(&y), sizeof(y)); }

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date