files.cxx 847 B

123456789101112131415161718192021222324252627282930313233343536
  1. //
  2. // files.cxx
  3. // gameutils
  4. //
  5. // Created by Sam Jaffe on 5/19/19.
  6. // Copyright © 2019 Sam Jaffe. All rights reserved.
  7. //
  8. #include "game/util/files.hpp"
  9. #include "scope_guard/scope_guard.hpp"
  10. namespace files {
  11. std::unique_ptr<char[]> load(std::string const & absolute_path) {
  12. FILE * fp = fopen(absolute_path.c_str(), "r");
  13. if (!fp) { return nullptr; }
  14. scope(exit) { fclose(fp); };
  15. // Determine file size
  16. fseek(fp, 0, SEEK_END);
  17. long size = ftell(fp);
  18. if (size < 0) { return nullptr; }
  19. std::unique_ptr<char[]> buffer{new char[size + 1]};
  20. rewind(fp);
  21. size_t read = fread(buffer.get(), sizeof(char), size, fp);
  22. if (read != static_cast<size_t>(size)) {
  23. fputs("Error reading file", stderr);
  24. return nullptr;
  25. } else {
  26. buffer[read + 1] = '\0';
  27. }
  28. return buffer;
  29. }
  30. }