Пример #1
0
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;
    }

}
Пример #2
0
//Iterates through all people in the AddressBook and prints info about them
void ListPeople(const AddressBook& address_book)
{
for(int i=0; i < address_book.person_size(); i++)
{
const Person& person = address_book.person(i);

cout << "Person ID: " << person.id() << endl;
cout << "  Name: " << person.name() << endl;
if(person.has_email())
{
cout << "  E-mail address: " << person.email() << endl;
}

for(int j=0; j < person.phone_size(); j++)
{
const Person::PhoneNumber& phone_number = person.phone(j);

switch(phone_number.type())
{
case Person::MOBILE:
cout << "  Mobile phone #: ";
break;

case Person::HOME:
cout << "  Home phone #: ";
break;

case Person::WORK:
cout << "  Work phone #: ";
break;
}

cout << phone_number.number() << endl;
}

}
}