FileReader.cpp 2.0 KB

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