1 // See README.txt for information and build instructions. 2 3 #include <fstream> 4 #include <google/protobuf/util/time_util.h> 5 #include <iostream> 6 #include <string> 7 8 #include "addressbook.pb.h" 9 10 using namespace std; 11 12 using google::protobuf::util::TimeUtil; 13 14 // Iterates though all people in the AddressBook and prints info about them. ListPeople(const tutorial::AddressBook & address_book)15void ListPeople(const tutorial::AddressBook& address_book) { 16 for (int i = 0; i < address_book.people_size(); i++) { 17 const tutorial::Person& person = address_book.people(i); 18 19 cout << "Person ID: " << person.id() << endl; 20 cout << " Name: " << person.name() << endl; 21 if (person.email() != "") { 22 cout << " E-mail address: " << person.email() << endl; 23 } 24 25 for (int j = 0; j < person.phones_size(); j++) { 26 const tutorial::Person::PhoneNumber& phone_number = person.phones(j); 27 28 switch (phone_number.type()) { 29 case tutorial::Person::MOBILE: 30 cout << " Mobile phone #: "; 31 break; 32 case tutorial::Person::HOME: 33 cout << " Home phone #: "; 34 break; 35 case tutorial::Person::WORK: 36 cout << " Work phone #: "; 37 break; 38 default: 39 cout << " Unknown phone #: "; 40 break; 41 } 42 cout << phone_number.number() << endl; 43 } 44 if (person.has_last_updated()) { 45 cout << " Updated: " << TimeUtil::ToString(person.last_updated()) << endl; 46 } 47 } 48 } 49 50 // Main function: Reads the entire address book from a file and prints all 51 // the information inside. main(int argc,char * argv[])52int main(int argc, char* argv[]) { 53 // Verify that the version of the library that we linked against is 54 // compatible with the version of the headers we compiled against. 55 GOOGLE_PROTOBUF_VERIFY_VERSION; 56 57 if (argc != 2) { 58 cerr << "Usage: " << argv[0] << " ADDRESS_BOOK_FILE" << endl; 59 return -1; 60 } 61 62 tutorial::AddressBook address_book; 63 64 { 65 // Read the existing address book. 66 fstream input(argv[1], ios::in | ios::binary); 67 if (!address_book.ParseFromIstream(&input)) { 68 cerr << "Failed to parse address book." << endl; 69 return -1; 70 } 71 } 72 73 ListPeople(address_book); 74 75 // Optional: Delete all global objects allocated by libprotobuf. 76 google::protobuf::ShutdownProtobufLibrary(); 77 78 return 0; 79 } 80