This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Tuesday, February 28, 2023

Write a program to demonstrate writing an object to a data file and reading it back.

 Here is a program that demonstrates writing an object to a data file and reading it back:

#include <iostream>
#include <fstream>
using namespace std;
class Student {
    private:
        string name;
        int roll;
    public:
        void setName(string n) {
            name = n;
        }
        void setRoll(int r) {
            roll = r;
        }
        void display() {
            cout << "Name: " << name << endl;
            cout << "Roll: " << roll << endl;
        }
};
int main() {
    Student s1;
    s1.setName("John");
    s1.setRoll(101);

    // Writing object to data file
    ofstream outFile("student.dat", ios::binary);
    outFile.write(reinterpret_cast<char*>(&s1), sizeof(Student));
    outFile.close();

    // Reading object from data file
    ifstream inFile("student.dat", ios::binary);
    Student s2;
    inFile.read(reinterpret_cast<char*>(&s2), sizeof(Student));
    s2.display();
    inFile.close();
    return 0;
}

In this program, we have defined a Student class with two data members name and roll. We have also defined setter functions setName() and setRoll() to set the values of these data members, and a display() function to display the values.

In the main() function, we create an object s1 of the Student class and set its name and roll using the setter functions.

We then create an output file stream object outFile and open a binary file named "student.dat". We use the write() function to write the object s1 to the file. We need to cast the address of the object to a char* type using reinterpret_cast.

Next, we create an input file stream object inFile and open the same binary file. We create an object s2 of the Student class to read the object from the file. We use the read() function to read the object from the file. Again, we need to cast the address of the object to a char* type using reinterpret_cast.

Finally, we call the display() function of the s2 object to display the values read from the file.

Output:

Name: John
Roll: 101

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget