file.cc 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* Copyright (c) 2017, Google Inc.
  2. *
  3. * Permission to use, copy, modify, and/or distribute this software for any
  4. * purpose with or without fee is hereby granted, provided that the above
  5. * copyright notice and this permission notice appear in all copies.
  6. *
  7. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  14. #include <openssl/bytestring.h>
  15. #include <errno.h>
  16. #include <stdio.h>
  17. #include <string.h>
  18. #include <algorithm>
  19. #include <vector>
  20. #include "internal.h"
  21. bool ReadAll(std::vector<uint8_t> *out, FILE *file) {
  22. out->clear();
  23. constexpr size_t kMaxSize = 1024 * 1024;
  24. size_t len = 0;
  25. out->resize(128);
  26. for (;;) {
  27. len += fread(out->data() + len, 1, out->size() - len, file);
  28. if (feof(file)) {
  29. out->resize(len);
  30. return true;
  31. }
  32. if (ferror(file)) {
  33. return false;
  34. }
  35. if (len == out->size()) {
  36. if (out->size() == kMaxSize) {
  37. fprintf(stderr, "Input too large.\n");
  38. return false;
  39. }
  40. size_t cap = std::min(out->size() * 2, kMaxSize);
  41. out->resize(cap);
  42. }
  43. }
  44. }
  45. bool WriteToFile(const std::string &path, bssl::Span<const uint8_t> in) {
  46. ScopedFILE file(fopen(path.c_str(), "wb"));
  47. if (!file) {
  48. fprintf(stderr, "Failed to open '%s': %s\n", path.c_str(), strerror(errno));
  49. return false;
  50. }
  51. if (fwrite(in.data(), in.size(), 1, file.get()) != 1) {
  52. fprintf(stderr, "Failed to write to '%s': %s\n", path.c_str(),
  53. strerror(errno));
  54. return false;
  55. }
  56. return true;
  57. }