Need a project done?

C++ Programming Developer

Search This Blog

Showing posts with label read object. Show all posts
Showing posts with label read object. Show all posts

Read Object from File C++

After an object has been written in a file, you can read that object from file in C++.
I've written an object at Write Objct to File C++.

After writing this object, following is the program to read an object from a file.

#include <iostream>
#include <fstream>
using namespace std;

/////////////////////////////////////////////////////////////////////////////////////////////////
class person{
protected:
char name[80];
short age;
public:
void showData(){
cout << "Name: " << name << endl;
cout << "Age: " <<  age << endl;
}
};
/////////////////////////////////////////////////////////////////////////////////////////////////

int main(){
person pers;

//open file.
ifstream is("PERSON.DAT", ios::binary);
//read an object from this file.
is.read(reinterpret_cast<char*>(&pers), sizeof(person));
//after reading object from file, Show it.
pers.showData();
return 0;
}

Write and read Object in file C++


Write and read Object in file in C++.

#include <iostream>
#include <fstream>
using namespace std;
////////////////////////////////////////////////////////////////////////////////////////////
class person{
protected:
char name[80];
short age;
public:
void getData(){
cout << "Enter name: "; cin >> name;
cout << "Enter age: "; cin >> age;
}
void showData(){
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
////////////////////////////////////////////////////////////////////////////////////////////
int main(){
person pers;
pers.getData();
ofstream os("person.txt", ios::binary);//Open file in binary mode.
cout << "This data has been store in the file person.txt in directory you've created your project" << endl;
cout << "Now Enter this data again, this data will not be saved" << endl;
os.write(reinterpret_cast<char*>(&pers), sizeof(pers));
pers.getData();
os.close();

//PRINTING SAVED DATA IN FILE.
ifstream is("person.txt",ios::binary);
is.read(reinterpret_cast<char*>(&pers),sizeof(pers));
pers.showData();//Here the data saved in file should have been displayed, but it's showing data not saved in file. WHY?
return 0;
}
"Don't let anyone ever make you feel like you don't deserve what you want."