Read/Write Class Objects from/to File in C++
Given a file “Input.txt” in which every line has values same as instance variables of a class.
Read the values into the class’s object and do necessary operations.
Theory :
The data transfer is usually done using '>>'
and <<' operators. But if you have
a class with 4 data members and want
to write all 4 data members from its
object directly to a file or vice-versa,
we can do that using following syntax :
To write object's data members in a file :
// Here file_obj is an object of ofstream
file_obj.write((char *) & class_obj, sizeof(class_obj));
To read file's data members into an object :
// Here file_obj is an object of ifstream
file_obj.read((char *) & class_obj, sizeof(class_obj));
Examples:
Input :
Input.txt :
Michael 19 1806
Kemp 24 2114
Terry 21 2400
Operation : Print the name of the highest
rated programmer.
Output :
Terry
C++
#include <iostream>
#include <fstream>
using namespace std;
class Contestant {
public :
string Name;
int Age, Ratings;
int input();
int output_highest_rated();
};
int Contestant::input()
{
ofstream file_obj;
file_obj.open( "Input.txt" , ios::app);
Contestant obj;
string str = "Michael" ;
int age = 18, ratings = 2500;
obj.Name = str;
obj.Age = age;
obj.Ratings = ratings;
file_obj.write(( char *)&obj, sizeof (obj));
str = "Terry" ;
age = 21;
ratings = 3200;
obj.Name = str;
obj.Age = age;
obj.Ratings = ratings;
file_obj.write(( char *)&obj, sizeof (obj));
file_obj.close();
return 0;
}
int Contestant::output_highest_rated()
{
ifstream file_obj;
file_obj.open( "Input.txt" , ios::in);
Contestant obj;
file_obj.read(( char *)&obj, sizeof (obj));
int max = 0;
string Highest_rated;
while (!file_obj.eof()) {
if (obj.Ratings > max) {
max = obj.Ratings;
Highest_rated = obj.Name;
}
file_obj.read(( char *)&obj, sizeof (obj));
}
file_obj.close();
cout << Highest_rated;
return 0;
}
int main()
{
Contestant object;
object.input();
object.output_highest_rated();
return 0;
}
|
Output:
Terry
Last Updated :
24 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...