CFileInputStream.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * CFileInputStream.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CFileInputStream.h"
  12. CFileInputStream::CFileInputStream(const boost::filesystem::path & file, si64 start, si64 size)
  13. : dataStart{start},
  14. dataSize{size},
  15. fileStream{file, std::ios::in | std::ios::binary}
  16. {
  17. if (fileStream.fail())
  18. throw std::runtime_error("File " + file.string() + " isn't available.");
  19. if (dataSize == 0)
  20. {
  21. fileStream.seekg(0, std::ios::end);
  22. dataSize = tell();
  23. }
  24. fileStream.seekg(dataStart, std::ios::beg);
  25. }
  26. si64 CFileInputStream::read(ui8 * data, si64 size)
  27. {
  28. si64 origin = tell();
  29. si64 toRead = std::min(dataSize - origin, size);
  30. fileStream.read(reinterpret_cast<char *>(data), toRead);
  31. return fileStream.gcount();
  32. }
  33. si64 CFileInputStream::seek(si64 position)
  34. {
  35. fileStream.seekg(dataStart + std::min(position, dataSize));
  36. return tell();
  37. }
  38. si64 CFileInputStream::tell()
  39. {
  40. return static_cast<si64>(fileStream.tellg()) - dataStart;
  41. }
  42. si64 CFileInputStream::skip(si64 delta)
  43. {
  44. si64 origin = tell();
  45. //ensure that we're not seeking past the end of real data
  46. si64 toSeek = std::min(dataSize - origin, delta);
  47. fileStream.seekg(toSeek, std::ios::cur);
  48. return tell() - origin;
  49. }
  50. si64 CFileInputStream::getSize()
  51. {
  52. return dataSize;
  53. }