user3611818
user3611818

Reputation: 247

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.

Upvotes: 0

Views: 1972

Answers (2)

lodo
lodo

Reputation: 2383

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.

Upvotes: 2

Nik Bougalis
Nik Bougalis

Reputation: 10613

Don't reinvent the wheel: use the Boost serialization libraries.

Upvotes: 1

Related Questions