C++ : How to read or write objects in file | Serializing & Deserializing Objects

In this article we will discuss how to write objects to file and how to read them back from to file and fill in object.

Suppose we have a class Student i.e.

class Student
{
public:
	std::string mName;
	std::string mId;
	std::string mPhoneNumber;

	Student(std::string id = "", std::string name = "", std::string phone = "") : mId(id), mName(name), mPhoneNumber(phone)
	{}

	bool operator==(const Student & obj)
	{
		return (mId == obj.mId) && (mName == obj.mName) && (mPhoneNumber == obj.mPhoneNumber);
	}

};

Writing objects in File | Serializing Objects

To write an object in file we need to over load << operator for the file as friend function i.e.

/*
 * Write the member variables to stream objects
 */
friend std::ostream & operator << (std::ostream &out, const Student & obj)
{
	out << obj.mId << "\n" <<obj.mName<<"\n"<<obj.mPhoneNumber<<std::endl;
	return out;
}

Now we can create Student class objects and store them in file i.e.
Student stud1("1","Jack", "4445554455");
Student stud2("4","Riti", "4445511111");
Student stud3("6","Aadi", "4040404011");

// Open the File
std::ofstream out("students.txt");

// Write objects to file
out<<stud1;
out<<stud2;
out<<stud3;

out.close();

Contents of file students.txt will be,
1
Jack
4445554455
4
Riti
4445511111
6
Aadi
4040404011

Reading objects from File | Deserializing Objects

To read an object in file we need to overload >> operator for the file as friend function i.e.

/*
 * Read data from stream object and fill it in member variables
 */
friend std::istream & operator >> (std::istream &in,  Student &obj)
{
	in >> obj.mId;
	in >> obj.mName;
	in >> obj.mPhoneNumber;
	return in;
}

Now we can load data in Student class objects from file i.e.
// Open the File
std::ifstream in("students.txt");

Student student1;
Student student2;
Student student3;

// Read objects from file and fill in data
in>>student1;
in>>student2;
in>>student3;

in.close();

Checkout complete example as follows,
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cassert>

class Student
{
public:
	std::string mName;
	std::string mId;
	std::string mPhoneNumber;

	Student(std::string id = "", std::string name = "", std::string phone = "") : mId(id), mName(name), mPhoneNumber(phone)
	{}

	bool operator==(const Student & obj)
	{
		return (mId == obj.mId) && (mName == obj.mName) && (mPhoneNumber == obj.mPhoneNumber);
	}

	/*
	 * Write the member variables to stream objects
	 */
	friend std::ostream & operator << (std::ostream &out, const Student & obj)
	{
		out << obj.mId << "\n" <<obj.mName<<"\n"<<obj.mPhoneNumber<<std::endl;
		return out;
	}
	/*
	 * Read data from stream object and fill it in member variables
	 */
	friend std::istream & operator >> (std::istream &in,  Student &obj)
	{
		in >> obj.mId;
		in >> obj.mName;
		in >> obj.mPhoneNumber;
		return in;
	}


};

int main()
{
	Student stud1("1","Jack", "4445554455");
	Student stud2("4","Riti", "4445511111");
	Student stud3("6","Aadi", "4040404011");

	// Open the File
	std::ofstream out("students.txt");

	// Write objects to file
	out<<stud1;
	out<<stud2;
	out<<stud3;

	out.close();

	// Open the File
	std::ifstream in("students.txt");

	Student student1;
	Student student2;
	Student student3;

	// Read objects from file and fill in data
	in>>student1;
	in>>student2;
	in>>student3;

	in.close();

	// Compare the Objects
	assert(stud1==student1);
	assert(stud2==student2);
	assert(stud3==student3);

	return 0;
}

To compile the above example in linux use following command,

g++ –std=c++11 example.cpp

Advertisements

Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top