CDirectory.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include <sys/stat.h>
  2. #include "CDirectory.h"
  3. #include "CAssetLoadException.h"
  4. using namespace WallpaperEngine::Assets;
  5. CDirectory::CDirectory (std::string basepath) :
  6. m_basepath (std::move (basepath))
  7. {
  8. // ensure the specified path exists
  9. struct stat buffer;
  10. if (stat (this->m_basepath.c_str (), &buffer) != 0)
  11. throw std::runtime_error ("Cannot find " + this->m_basepath + ". This folder is required for wallpaper engine to work");
  12. if (!S_ISDIR(buffer.st_mode))
  13. throw std::runtime_error ("Cannot find " + this->m_basepath + ". There's an assets file in it's place");
  14. }
  15. CDirectory::~CDirectory ()
  16. {
  17. }
  18. const void* CDirectory::readFile (std::string filename, uint32_t* length) const
  19. {
  20. std::string final = this->m_basepath + filename;
  21. // first check the cache, if the file is there already just return the data in there
  22. auto it = this->m_cache.find (final);
  23. if (it != this->m_cache.end ())
  24. {
  25. if (length != nullptr)
  26. *length = (*it).second.length;
  27. return (*it).second.address;
  28. }
  29. FILE* fp = fopen (final.c_str (), "rb");
  30. if (fp == nullptr)
  31. throw CAssetLoadException(filename, "Cannot find file");
  32. // go to the end, get the position and return to the beginning
  33. fseek (fp, 0, SEEK_END);
  34. long size = ftell (fp);
  35. fseek (fp, 0, SEEK_SET);
  36. // now read the whole file
  37. char* contents = new char[size];
  38. if (fread (contents, size, 1, fp) != 1)
  39. {
  40. delete[] contents;
  41. throw CAssetLoadException (filename, "Unexpected error when reading the file");
  42. }
  43. if (length != nullptr)
  44. *length = size;
  45. return contents;
  46. }