filecache.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. Copyright (C) 2013 Jonathan Neuschäfer <j.neuschaefer@gmx.net>
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU Lesser General Public License as published by
  7. the Free Software Foundation; either version 3.0 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public License along
  14. with this program; if not, write to the Free Software Foundation, Inc.,
  15. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  16. */
  17. #include "filecache.h"
  18. #include "network/networkprotocol.h"
  19. #include "log.h"
  20. #include "filesys.h"
  21. #include <string>
  22. #include <iostream>
  23. #include <fstream>
  24. #include <stdlib.h>
  25. bool FileCache::loadByPath(const std::string &path, std::ostream &os)
  26. {
  27. std::ifstream fis(path.c_str(), std::ios_base::binary);
  28. if(!fis.good()){
  29. verbosestream<<"FileCache: File not found in cache: "
  30. <<path<<std::endl;
  31. return false;
  32. }
  33. bool bad = false;
  34. for(;;){
  35. char buf[1024];
  36. fis.read(buf, 1024);
  37. std::streamsize len = fis.gcount();
  38. os.write(buf, len);
  39. if(fis.eof())
  40. break;
  41. if(!fis.good()){
  42. bad = true;
  43. break;
  44. }
  45. }
  46. if(bad){
  47. errorstream<<"FileCache: Failed to read file from cache: \""
  48. <<path<<"\""<<std::endl;
  49. }
  50. return !bad;
  51. }
  52. bool FileCache::updateByPath(const std::string &path, const std::string &data)
  53. {
  54. std::ofstream file(path.c_str(), std::ios_base::binary |
  55. std::ios_base::trunc);
  56. if(!file.good())
  57. {
  58. errorstream<<"FileCache: Can't write to file at "
  59. <<path<<std::endl;
  60. return false;
  61. }
  62. file.write(data.c_str(), data.length());
  63. file.close();
  64. return !file.fail();
  65. }
  66. bool FileCache::update(const std::string &name, const std::string &data)
  67. {
  68. std::string path = m_dir + DIR_DELIM + name;
  69. return updateByPath(path, data);
  70. }
  71. bool FileCache::load(const std::string &name, std::ostream &os)
  72. {
  73. std::string path = m_dir + DIR_DELIM + name;
  74. return loadByPath(path, os);
  75. }