FileStream.cpp 1.1 KB

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