FileSystem.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "Base.h"
  2. #include "FileSystem.h"
  3. namespace gameplay
  4. {
  5. static std::string __resourcePath("./");
  6. FileSystem::FileSystem()
  7. {
  8. }
  9. FileSystem::~FileSystem()
  10. {
  11. }
  12. void FileSystem::setResourcePath(const char* path)
  13. {
  14. __resourcePath = path == NULL ? "" : path;
  15. }
  16. const char* FileSystem::getResourcePath()
  17. {
  18. return __resourcePath.c_str();
  19. }
  20. FILE* FileSystem::openFile(const char* path, const char* mode)
  21. {
  22. std::string fullPath(__resourcePath);
  23. fullPath += path;
  24. FILE* fp = fopen(fullPath.c_str(), mode);
  25. // Win32 doesnt support a asset or bundle definitions.
  26. #ifdef WIN32
  27. if (fp == NULL)
  28. {
  29. fullPath = __resourcePath;
  30. fullPath += "../../gameplay/";
  31. fullPath += path;
  32. fp = fopen(fullPath.c_str(), mode);
  33. }
  34. #endif
  35. return fp;
  36. }
  37. char* FileSystem::readAll(const char* filePath, int* fileSize)
  38. {
  39. // Open file for reading.
  40. FILE* file = openFile(filePath, "rb");
  41. if (file == NULL)
  42. {
  43. LOG_ERROR_VARG("Failed to load file: %s", filePath);
  44. return NULL;
  45. }
  46. // Obtain file length.
  47. fseek(file, 0, SEEK_END);
  48. int size = (int)ftell(file);
  49. fseek(file, 0, SEEK_SET);
  50. // Read entire file contents.
  51. char* buffer = new char[size + 1];
  52. int read = (int)fread(buffer, 1, size, file);
  53. assert(read == size);
  54. if (read != size)
  55. {
  56. LOG_ERROR_VARG("Read error for file: %s (%d < %d)", filePath, (int)read, (int)size);
  57. SAFE_DELETE_ARRAY(buffer);
  58. return NULL;
  59. }
  60. // Force the character buffer to be NULL-terminated.
  61. buffer[size] = '\0';
  62. // Close file and return.
  63. fclose(file);
  64. if (fileSize)
  65. {
  66. *fileSize = size;
  67. }
  68. return buffer;
  69. }
  70. }