list_people.cc 2.2 KB

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