How to write an object to file in C++

You can override operator>> and operator<< to read/write to stream.

Example Entry struct with some values:

struct Entry2
{
    string original;
    string currency;

    Entry2() {}
    Entry2(string& in);
    Entry2(string& original, string& currency)
        : original(original), currency(currency)
    {}
};


istream& operator>>(istream& is, Entry2& en);
ostream& operator<<(ostream& os, const Entry2& en);

Implementation:

using namespace std;

istream& operator>>(istream& is, Entry2& en)
{
    is >> en.original;
    is >> en.currency;
    return is;
}

ostream& operator<<(ostream& os, const Entry2& en)
{
    os << en.original << " " << en.currency;
    return os;
}

Then you open filestream, and for each object you call:

ifstream in(filename.c_str());
Entry2 e;
in >> e;
//if you want to use read: 
//in.read(reinterpret_cast<const char*>(&e),sizeof(e));
in.close();

Or output:

Entry2 e;
// set values in e
ofstream out(filename.c_str());
out << e;
out.close();

Or if you want to use stream read and write then you just replace relevant code in operators implementation.

When the variables are private inside your struct/class then you need to declare operators as friend methods.

You implement any format/separators that you like. When your string include spaces use getline() that takes a string and stream instead of >> because operator>> uses spaces as delimiters by default. Depends on your separators.

Leave a Comment