encode_stream.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /* Same as test_encode1.c, except writes directly to stdout.
  2. */
  3. #include <stdio.h>
  4. #include <pb_encode.h>
  5. #include "person.pb.h"
  6. #include "test_helpers.h"
  7. /* This binds the pb_ostream_t into the stdout stream */
  8. bool streamcallback(pb_ostream_t *stream, const uint8_t *buf, size_t count)
  9. {
  10. FILE *file = (FILE*) stream->state;
  11. return fwrite(buf, 1, count, file) == count;
  12. }
  13. int main()
  14. {
  15. /* Initialize the structure with constants */
  16. Person person = {"Test Person 99", 99, true, "test@person.com",
  17. 3, {{"555-12345678", true, Person_PhoneType_MOBILE},
  18. {"99-2342", false, 0},
  19. {"1234-5678", true, Person_PhoneType_WORK},
  20. }};
  21. /* Prepare the stream, output goes directly to stdout */
  22. pb_ostream_t stream = {&streamcallback, NULL, SIZE_MAX, 0};
  23. stream.state = stdout;
  24. SET_BINARY_MODE(stdout);
  25. /* Now encode it and check if we succeeded. */
  26. if (pb_encode(&stream, Person_fields, &person))
  27. {
  28. return 0; /* Success */
  29. }
  30. else
  31. {
  32. fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream));
  33. return 1; /* Failure */
  34. }
  35. }