FileReader.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include "io/FileReader.h"
  2. #include <stdio.h>
  3. #include "utils/Logger.h"
  4. Core::FileReader::FileReader() : file(nullptr) {
  5. }
  6. Core::FileReader::FileReader(FileReader&& other) : FileReader() {
  7. swap(other);
  8. }
  9. Core::FileReader::~FileReader() {
  10. if(file != nullptr) {
  11. int r = fclose(static_cast<FILE*>(file));
  12. if(r != 0) {
  13. CORE_LOG_WARNING("Cannot close file #: #", path, r);
  14. }
  15. file = nullptr;
  16. }
  17. }
  18. Core::FileReader& Core::FileReader::operator=(FileReader&& other) {
  19. swap(other);
  20. return *this;
  21. }
  22. const Core::Path& Core::FileReader::getPath() const {
  23. return path;
  24. }
  25. Core::Error Core::FileReader::open(const Path& p) {
  26. if(file != nullptr) {
  27. return Error::INVALID_STATE;
  28. }
  29. path = p;
  30. file = fopen(path, "rb");
  31. return file != nullptr ? Error::NONE : Error::CANNOT_OPEN_FILE;
  32. }
  33. Core::Error Core::FileReader::open(const char* p) {
  34. if(file != nullptr) {
  35. return Error::INVALID_STATE;
  36. }
  37. CORE_RETURN_ERROR(path.append(p));
  38. file = fopen(path, "rb");
  39. return file != nullptr ? Error::NONE : Error::CANNOT_OPEN_FILE;
  40. }
  41. Core::Error Core::FileReader::readChar(int& c) {
  42. if(file == nullptr) {
  43. return Error::INVALID_STATE;
  44. }
  45. c = fgetc(static_cast<FILE*>(file));
  46. return c == EOF ? Error::END_OF_FILE : Error::NONE;
  47. }
  48. Core::Error Core::FileReader::readChars(char* buffer, int bufferSize) {
  49. if(file == nullptr) {
  50. return Error::INVALID_STATE;
  51. } else if(bufferSize <= 0) {
  52. return Error::INVALID_ARGUMENT;
  53. }
  54. size_t size = static_cast<size_t>(bufferSize - 1);
  55. size_t readBytes = fread(buffer, 1, size, static_cast<FILE*>(file));
  56. buffer[readBytes] = '\0';
  57. return readBytes != size ? Error::END_OF_FILE : Error::NONE;
  58. }
  59. void Core::FileReader::swap(FileReader& other) {
  60. Core::swap(file, other.file);
  61. Core::swap(path, other.path);
  62. }