CFileInputStream.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. #include "../ExceptionsCommon.h"
  13. VCMI_LIB_NAMESPACE_BEGIN
  14. CFileInputStream::CFileInputStream(const boost::filesystem::path & file, si64 start, si64 size)
  15. : dataStart{start},
  16. dataSize{size},
  17. fileStream{file.c_str(), std::ios::in | std::ios::binary}
  18. {
  19. if (fileStream.fail())
  20. throw DataLoadingException("Failed to open file '" + file.string() + "'. Reason: " + strerror(errno) );
  21. if (dataSize == 0)
  22. {
  23. fileStream.seekg(0, std::ios::end);
  24. dataSize = tell();
  25. }
  26. fileStream.seekg(dataStart, std::ios::beg);
  27. }
  28. si64 CFileInputStream::read(ui8 * data, si64 size)
  29. {
  30. si64 origin = tell();
  31. si64 toRead = std::min(dataSize - origin, size);
  32. fileStream.read(reinterpret_cast<char *>(data), toRead);
  33. return fileStream.gcount();
  34. }
  35. si64 CFileInputStream::seek(si64 position)
  36. {
  37. fileStream.seekg(dataStart + std::min(position, dataSize));
  38. return tell();
  39. }
  40. si64 CFileInputStream::tell()
  41. {
  42. return static_cast<si64>(fileStream.tellg()) - dataStart;
  43. }
  44. si64 CFileInputStream::skip(si64 delta)
  45. {
  46. si64 origin = tell();
  47. //ensure that we're not seeking past the end of real data
  48. si64 toSeek = std::min(dataSize - origin, delta);
  49. fileStream.seekg(toSeek, std::ios::cur);
  50. return tell() - origin;
  51. }
  52. si64 CFileInputStream::getSize()
  53. {
  54. return dataSize;
  55. }
  56. VCMI_LIB_NAMESPACE_END