void read_write_read_with_mergefrom(const string &filename, AddressBook &book) { { fstream read_f(filename.c_str(), ios::in | ios::binary); if (!read_f) { cerr << filename << ": file not found, exit..." << endl; return; } book.ParseFromIstream(&read_f); cout << "book: " << book.DebugString() << endl; } book.set_host_name("carl_update_mergefrom"); int index = 0; for (; index < book.person_size(); ++index) { Person person; person.CopyFrom(book.person(index)); person.set_age(100); book.mutable_person(index)->MergeFrom(person); } { fstream write_f(filename.c_str(), ios::out | ios::trunc | ios::binary); if (!book.SerializeToOstream(&write_f)) { cerr << "failed to write addressbook" << endl; return; } } { fstream read_f(filename.c_str(), ios::in | ios::binary); if (!read_f) { cerr << filename << ": file not found, exit..." << endl; return; } book.ParseFromIstream(&read_f); cout << "book: " << book.DebugString() << endl; } }