FileSystem.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright (C) 2022 The V-Gears Team
  3. *
  4. * This file is part of V-Gears
  5. *
  6. * V-Gears is free software: you can redistribute it and/or modify it under
  7. * terms of the GNU General Public License as published by the Free Software
  8. * Foundation, version 3.0 (GPLv3) of the License.
  9. *
  10. * V-Gears is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. */
  15. #include <stdio.h>
  16. #include "common/FileSystem.h"
  17. #include "core/Logger.h"
  18. unsigned int FileSystem::GetFileSize(const Ogre::String &path){
  19. FILE* file = fopen(path.c_str(), "rb");
  20. if (file == nullptr){
  21. LOG_ERROR("Can't open file " + path + ".\n");
  22. return 0;
  23. }
  24. // Set cursor to end of file
  25. fseek(file, 0, SEEK_END);
  26. unsigned int size = ftell(file);
  27. fclose(file);
  28. return size;
  29. }
  30. bool FileSystem::ReadFile(
  31. const Ogre::String &path, void* buffer,
  32. const unsigned int start, const unsigned int length
  33. ){
  34. FILE* file = fopen(path.c_str(), "rb");
  35. if (file == nullptr){
  36. LOG_ERROR("Can't open file " + path + ".\n");
  37. return false;
  38. }
  39. fseek(file, start, SEEK_SET);
  40. const auto ret = fread(buffer, sizeof(char), length, file);
  41. fclose(file);
  42. if (ret != sizeof(char) * length){
  43. LOG_ERROR("Failed to read all data\n");
  44. return false;
  45. }
  46. return true;
  47. }
  48. bool FileSystem::WriteFile(
  49. const Ogre::String &path, const void* buffer, const unsigned int length
  50. ){
  51. FILE* file = fopen(path.c_str(), "ab");
  52. if (file == nullptr) return false;
  53. fwrite(buffer, sizeof(char), length, file);
  54. fclose(file);
  55. return true;
  56. }
  57. bool FileSystem::WriteNewFile(
  58. const Ogre::String &path, const void* buffer, unsigned int length
  59. ){
  60. RemoveFile(path);
  61. return !! (WriteFile(path, buffer, length));
  62. }
  63. bool FileSystem::RemoveFile(const Ogre::String &path){
  64. return (remove(path.c_str()) == 0);
  65. }