CDirectory.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include "CDirectory.h"
  2. using namespace WallpaperEngine::Assets;
  3. CDirectory::CDirectory (std::string basepath) :
  4. m_basepath (std::move (basepath))
  5. {
  6. }
  7. CDirectory::~CDirectory ()
  8. {
  9. }
  10. void* CDirectory::readFile (std::string filename, uint32_t* length)
  11. {
  12. std::string final = this->m_basepath + filename;
  13. // first check the cache, if the file is there already just return the data in there
  14. auto it = this->m_cache.find (final);
  15. if (it != this->m_cache.end ())
  16. {
  17. if (length != nullptr)
  18. *length = (*it).second.length;
  19. return (*it).second.address;
  20. }
  21. FILE* fp = fopen (final.c_str (), "rb");
  22. if (fp == nullptr)
  23. throw std::runtime_error ("Cannot find requested file");
  24. // go to the end, get the position and return to the beginning
  25. fseek (fp, 0, SEEK_END);
  26. long size = ftell (fp);
  27. fseek (fp, 0, SEEK_SET);
  28. // now read the whole file
  29. char* contents = new char[size];
  30. if (fread (contents, size, 1, fp) != 1)
  31. {
  32. delete[] contents;
  33. throw std::runtime_error ("Unexpected error when reading the file");
  34. }
  35. // store it in the cache too
  36. this->m_cache.insert (std::make_pair <std::string, CFileEntry> (
  37. std::move (final),
  38. CFileEntry (contents, size)
  39. ));
  40. if (length != nullptr)
  41. *length = size;
  42. return contents;
  43. }