hipack-cat.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * hipack-cat.c
  3. * Copyright (C) 2015 Adrian Perez <aperez@igalia.com>
  4. *
  5. * Distributed under terms of the MIT license.
  6. */
  7. #define _POSIX_C_SOURCE 2
  8. #include "../hipack.h"
  9. #include <stdlib.h>
  10. #include <unistd.h>
  11. #include <errno.h>
  12. static void
  13. usage (const char *argv0, int code)
  14. {
  15. FILE *output = (code == EXIT_FAILURE) ? stderr : stdout;
  16. fprintf (output, "Usage: %s [-c] PATH\n", argv0);
  17. exit (code);
  18. }
  19. int
  20. main (int argc, char *argv[])
  21. {
  22. bool compact = false;
  23. int opt;
  24. while ((opt = getopt (argc, argv, "hc")) != -1) {
  25. switch (opt) {
  26. case 'c':
  27. compact = true;
  28. break;
  29. case 'h':
  30. usage (argv[0], EXIT_SUCCESS);
  31. break;
  32. default:
  33. usage (argv[0], EXIT_FAILURE);
  34. }
  35. }
  36. if (optind >= argc) {
  37. usage (argv[0], EXIT_FAILURE);
  38. }
  39. FILE *fp = fopen (argv[optind], "rb");
  40. if (!fp) {
  41. fprintf (stderr, "%s: Cannot open '%s' (%s)\n",
  42. argv[0], argv[optind], strerror (errno));
  43. return EXIT_FAILURE;
  44. }
  45. int retcode = EXIT_SUCCESS;
  46. hipack_reader_t reader = {
  47. .getchar = hipack_stdio_getchar,
  48. .getchar_data = fp,
  49. };
  50. hipack_dict_t *message = hipack_read (&reader);
  51. if (!message) {
  52. assert (reader.error);
  53. fprintf (stderr, "line %u, column %u: %s\n",
  54. reader.error_line, reader.error_column,
  55. (reader.error == HIPACK_READ_ERROR)
  56. ? strerror (errno) : reader.error);
  57. retcode = EXIT_FAILURE;
  58. goto cleanup;
  59. }
  60. hipack_writer_t writer = {
  61. .putchar = hipack_stdio_putchar,
  62. .putchar_data = stdout,
  63. .indent = compact ? HIPACK_WRITER_COMPACT : HIPACK_WRITER_INDENTED,
  64. };
  65. hipack_write (&writer, message);
  66. cleanup:
  67. fclose (fp);
  68. hipack_dict_free (message);
  69. return retcode;
  70. }