Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

49 rader
1.4 KiB

  1. //
  2. // Lol Engine
  3. //
  4. // Copyright © 2010—2020 Sam Hocevar <sam@hocevar.net>
  5. //
  6. // Lol Engine is free software. It comes without any warranty, to
  7. // the extent permitted by applicable law. You can redistribute it
  8. // and/or modify it under the terms of the Do What the Fuck You Want
  9. // to Public License, Version 2, as published by the WTFPL Task Force.
  10. // See http://www.wtfpl.net/ for more details.
  11. //
  12. #pragma once
  13. //
  14. // The file-related classes
  15. // ————————————————————————
  16. // These do not use std::filesystem yet because of the stdc++fs link requirement.
  17. //
  18. #include <fstream> // std::ofstream
  19. namespace lol::file
  20. {
  21. template<typename T, typename U = typename T::value_type>
  22. static inline bool read(std::string const &path, T &data)
  23. {
  24. std::ifstream f(path, std::ios::in | std::ios::binary | std::ios::ate);
  25. auto file_size = f.tellg(); // works because std::ios::ate
  26. if (file_size < 0)
  27. return false;
  28. f.seekg(0, std::ios::beg);
  29. data.resize((size_t(file_size) + sizeof(U) - 1) / sizeof(U));
  30. f.read((char *)data.data(), file_size);
  31. return !f.fail();
  32. }
  33. template<typename T, typename U = typename T::value_type>
  34. static inline bool write(std::string const &path, T const &data)
  35. {
  36. std::ofstream f(path, std::ios::binary);
  37. f.write((char const *)data.data(), data.size() * sizeof(U));
  38. f.close();
  39. return !f.fail();
  40. }
  41. } // namespace lol::file