Need a project done?

C++ Programming Developer

Search This Blog

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;
}

No comments:

Post a Comment

"Don't let anyone ever make you feel like you don't deserve what you want."