FileReader.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Author: Patrick-Christopher Mattulat
  3. * Company: Lynar Studios
  4. * E-Mail: webmaster@lynarstudios.com
  5. * Created: 2020-08-17
  6. * Changed: 2025-12-21
  7. *
  8. * */
  9. #include <fstream>
  10. #include <limits>
  11. #include <ls-std/core/exception/FileOperationException.hpp>
  12. #include <ls-std/io/FileReader.hpp>
  13. #include <ls-std/io/evaluator/FileExistenceEvaluator.hpp>
  14. #include <stdexcept>
  15. using ls::std::core::Class;
  16. using ls::std::core::FileOperationException;
  17. using ls::std::core::type::byte_field;
  18. using ls::std::core::type::byte_type;
  19. using ls::std::io::File;
  20. using ls::std::io::FileExistenceEvaluator;
  21. using ls::std::io::FileReader;
  22. using std::ifstream;
  23. using std::numeric_limits;
  24. using std::overflow_error;
  25. using std::streamsize;
  26. using std::string;
  27. FileReader::FileReader(const File &_file) : Class("FileReader"), file(_file)
  28. {
  29. FileExistenceEvaluator{_file.getAbsoluteFilePath()}.evaluate();
  30. }
  31. FileReader::~FileReader() noexcept = default;
  32. byte_field FileReader::read()
  33. {
  34. ifstream inputStream{this->file.getAbsoluteFilePath(), ifstream::binary};
  35. const auto length = this->file.getSize();
  36. auto data = string(length, 'x');
  37. if (length > static_cast<size_t>(numeric_limits<streamsize>::max()))
  38. {
  39. throw overflow_error("file size too large to read");
  40. }
  41. inputStream.read(data.data(), static_cast<streamsize>(length));
  42. if (inputStream.fail())
  43. {
  44. throw FileOperationException{"operation: read"};
  45. }
  46. inputStream.close();
  47. return data;
  48. }
  49. void FileReader::reset(const File &_file)
  50. {
  51. FileExistenceEvaluator{_file.getAbsoluteFilePath()}.evaluate();
  52. this->file = _file;
  53. }