简体   繁体   中英

How to write and read class from binary file in c++

i am learning fstream in c++ and id like to write a class in binary, then retrieve it. and of course , it all went horribly wrong.

heres the class

class Student
{
private:
    const char* name;
    int age;
public:
    Student()
    {

    };
    Student(const char* name, int age) : name{ name }, age{ age }{};
    void display()
    {
        std::cout << "name : " << this->name << std::endl << "age : " << this->age << std::endl;
    }
};

the writting class (which i think works)

void writeDatabase()
{
    Student jack("jack", 21);
    std::ofstream file;
    file.open("data.dat", std::ios::binary);
    if (file.is_open())
    {
        file.write(reinterpret_cast<char*>(&jack), sizeof(jack));
        std::cout << "wrote to file";
    }
    else
    {
        std::cout << "error opening file when writing to database\n";
    }
    file.close();
}

where i am stuck

void readData()
{
    Student st;
    std::ifstream file;
    file.open("data.dat", std::ios::binary);
    if (file.is_open())
    {
        std::cout << "opened file\n";
        file.read(reinterpret_cast<char*>(&st), sizeof(st));
        st.display();
        file.close();
    }
    else
    {
        std::cout << "error opening file when reading\n";
    }
}

The issue here isn't that you're reading or writing the bytes from disk incorrectly. Rather, the problem you're running into is that those bytes don't mean what you intend them to mean.

Your class has a data member name that's a const char * . That's a pointer to some location in memory that contains the name. When you use the write function to write the data from your type to disk, it's storing that pointer on disk somewhere. When you then load the data from disk, it's reloading that pointer.

The problem is that the pointer isn't what you want to store. If you reload the pointer from disk, it'll point to the same spot in memory that it used to, but there's no reason to suspect that you'll find the student's name sitting in memory at the place it's pointing. If you've closed the program and then reopened it, you shouldn't see any memory from the previous run.

To fix this, you'll need to change how you write the data to disk. Instead of copying the raw bytes from the class, instead see if you can find a way to write out the name and the age in some way that you can then read that data back in. For example, maybe you'd write it to disk as the age, then a space, then the name.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM