filereader.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #ifdef READER_CPP
  2. #include "filereader.hpp"
  3. unsigned FileReader::size() {
  4. return fp.size();
  5. }
  6. //This function will allocate memory even if open() fails.
  7. //This is needed so that when SRAM files do not exist, the
  8. //memory for the SRAM data will be allocated still.
  9. //The memory is flushed to 0x00 when no file is opened.
  10. uint8_t* FileReader::read(unsigned length) {
  11. uint8_t *data = 0;
  12. if(length == 0) {
  13. //read the entire file into RAM
  14. data = new(zeromemory) uint8_t[fp.size()];
  15. if(fp.open()) fp.read(data, fp.size());
  16. } else if(length > fp.size()) {
  17. //read the entire file into RAM, pad the rest with 0x00s
  18. data = new(zeromemory) uint8_t[length];
  19. if(fp.open()) fp.read(data, fp.size());
  20. } else { //filesize >= length
  21. //read only what was requested
  22. data = new(zeromemory) uint8_t[length];
  23. if(fp.open()) fp.read(data, length);
  24. }
  25. return data;
  26. }
  27. bool FileReader::ready() {
  28. return fp.open();
  29. }
  30. FileReader::FileReader(const char *fn) {
  31. if(!fp.open(fn, file::mode_read)) return;
  32. if(fp.size() == 0) {
  33. //empty file
  34. fp.close();
  35. }
  36. }
  37. FileReader::~FileReader() {
  38. if(fp.open()) fp.close();
  39. }
  40. #endif //ifdef READER_CPP