简体   繁体   中英

C++ Read/Write struct object to a file

So i written a program where i can input 4 values a first name, last name, height and a signature. I store all values in a Vector but now i would like to learn how i can take the values from my vector and store them in a file and later on read from the file and store back into the vector.

vector<Data> dataVector;
struct Data info;
info.fname = "Testname";
info.lname = "Johnson";
info.signature = "test123";
info.height = 1.80;
dataVector.push_back(info);

Code looks like this i havent found anyway to store objects of a struct into a file so i'm asking the community for some help.

You should provide your struct with a method to write it to a stream:

struct Data
{
    // various things
    void write_to(ostream& output)
    {
        output << fname << "\n";
        output << lname << "\n";
        // and others
    }
    void read_from(istream& input)
    {
        input >> info.fname;
        input >> info.lname;
        // and others
    }
};

Or provide two freestanding functions to do the job, like this:

ostream& write(ostream& output, const Data& data)
{
    //like above
}
// and also read

Or, better, overload the << and >> operator:

ostream& operator<<(const Data& data)
{
    //like above
}
// you also have to overload >>

Or, even better, use an existing library, like Boost, that provides such functionality.

The last option has many pros: you don't have to think how to separate the fields of the struct in the file, how to save more instances in the same file, you have to do less work when refactoring or modifying the struct.

不要重新发明轮子:使用Boost序列化库。

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