简体   繁体   中英

How do I save an object containing a vector of another object into file and read back from file using binary files in C++?

This is my code for reading and Writing vectors; I get no errors while execution, but whenever I read back from it; it gives random values of integer instead of 50, and 100. What is it that I am doing wrong?

I have used vector objects inside of another object, and I am trying to file it using binary filing of objects.

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

class Rest{
    int value;
    public:
        void setvalue(int value){this->value=value;}
        int getvalue(){return value;}
};

class Admin{
    vector<Rest> restaurant;
    public:
        Admin(){}

        void setValue(int value){
            Rest obj1;
            Rest obj2;
            obj1.setvalue(value);
            obj2.setvalue(value+50);
            restaurant.push_back(obj1);
            restaurant.push_back(obj2);
        }
        vector<Rest> getRestFromFile(){
            Admin obj;
            fstream getsavedvector("Testsave.BIN", ios::in | ios::binary);
            getsavedvector.read(reinterpret_cast<char*> (&obj), sizeof(obj));
            getsavedvector.close();

            return obj.getRest();
        }
        void setRestVectorToFile(Admin obj){
            fstream savevector("Testsave.BIN", ios::out | ios::binary);
            savevector.write(reinterpret_cast<char*> (&obj),sizeof(obj));
            savevector.close();
        }
        void setRestVector(vector<Rest> restaurant){
            for(int i=0;i<restaurant.size();i++){
                this->restaurant.push_back(restaurant[i]);
            }
        }
        vector<Rest> getRest(){
            return this->restaurant;
        }
        void Display(){
            for(auto v: restaurant){
                cout<<v.getvalue()<<endl;
            }

        }
};

int main()
{    
    Admin obj;
    obj.setValue(50);
    obj.setRestVectorToFile(obj);

    Admin obj2;
    obj2.setRestVector(obj2.getRestFromFile());
    obj2.Display();
}

Basically what you're doing wrong is that you can't just cast C++ objects to char * and dump some bytes on disk and expect that to work. Now that is going to work in some limited circumstances like when you're just writing primitive objects like integers or structs containing only integers or something of the sort, but it's not going to work for more complex things like vectors. The correct way to do this would be to come up with or use an existing Serialization format, to get a proper encoding for vectors you can encode/decode between when writing to or reading from your file.

A very simple scheme you could use in this case without too many changes would be to first store the length of the vector, and then store each element in sequence afterwards. This is easy enough to read and write. If you want a more general solution you'll want to look at formats like JSON, msgpack, XML or even database management systems like SQLite or PostgreSQL. Which is the “correct” choice depends on your application, in this case especially if you're just learning about reading to and writing from files you could just roll your own simple format as an exercise.

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