CDirectory.cpp 1.7 KB

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