FileStream.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "FileStream.h"
  2. using namespace bell;
  3. FileStream::FileStream(const std::string& path, std::string read)
  4. {
  5. file = fopen(path.c_str(), "rb");
  6. if (file == NULL)
  7. {
  8. throw std::runtime_error("Could not open file: " + path);
  9. }
  10. }
  11. FileStream::~FileStream()
  12. {
  13. close();
  14. }
  15. size_t FileStream::read(uint8_t *buf, size_t nbytes)
  16. {
  17. if (file == NULL)
  18. {
  19. throw std::runtime_error("Stream is closed");
  20. }
  21. return fread(buf, 1, nbytes, file);
  22. }
  23. size_t FileStream::skip(size_t nbytes)
  24. {
  25. if (file == NULL)
  26. {
  27. throw std::runtime_error("Stream is closed");
  28. }
  29. return fseek(file, nbytes, SEEK_CUR);
  30. }
  31. size_t FileStream::position()
  32. {
  33. if (file == NULL)
  34. {
  35. throw std::runtime_error("Stream is closed");
  36. }
  37. return ftell(file);
  38. }
  39. size_t FileStream::size()
  40. {
  41. if (file == NULL)
  42. {
  43. throw std::runtime_error("Stream is closed");
  44. }
  45. size_t pos = ftell(file);
  46. fseek(file, 0, SEEK_END);
  47. size_t size = ftell(file);
  48. fseek(file, pos, SEEK_SET);
  49. return size;
  50. }
  51. void FileStream::close()
  52. {
  53. if (file != NULL)
  54. {
  55. fclose(file);
  56. file = NULL;
  57. }
  58. }