CReadFile.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. // Copyright (C) 2002-2012 Nikolaus Gebhardt
  2. // This file is part of the "Irrlicht Engine".
  3. // For conditions of distribution and use, see copyright notice in irrlicht.h
  4. #include "CReadFile.h"
  5. namespace irr
  6. {
  7. namespace io
  8. {
  9. CReadFile::CReadFile(const io::path& fileName)
  10. : File(0), FileSize(0), Filename(fileName)
  11. {
  12. #ifdef _DEBUG
  13. setDebugName("CReadFile");
  14. #endif
  15. openFile();
  16. }
  17. CReadFile::~CReadFile()
  18. {
  19. if (File)
  20. fclose(File);
  21. }
  22. //! returns how much was read
  23. s32 CReadFile::read(void* buffer, u32 sizeToRead)
  24. {
  25. if (!isOpen())
  26. return 0;
  27. return (s32)fread(buffer, 1, sizeToRead, File);
  28. }
  29. //! changes position in file, returns true if successful
  30. //! if relativeMovement==true, the pos is changed relative to current pos,
  31. //! otherwise from begin of file
  32. bool CReadFile::seek(long finalPos, bool relativeMovement)
  33. {
  34. if (!isOpen())
  35. return false;
  36. return fseek(File, finalPos, relativeMovement ? SEEK_CUR : SEEK_SET) == 0;
  37. }
  38. //! returns size of file
  39. long CReadFile::getSize() const
  40. {
  41. return FileSize;
  42. }
  43. //! returns where in the file we are.
  44. long CReadFile::getPos() const
  45. {
  46. return ftell(File);
  47. }
  48. //! opens the file
  49. void CReadFile::openFile()
  50. {
  51. if (Filename.size() == 0) // bugfix posted by rt
  52. {
  53. File = 0;
  54. return;
  55. }
  56. #if defined ( _IRR_WCHAR_FILESYSTEM )
  57. File = _wfopen(Filename.c_str(), L"rb");
  58. #else
  59. File = fopen(Filename.c_str(), "rb");
  60. #endif
  61. if (File)
  62. {
  63. // get FileSize
  64. fseek(File, 0, SEEK_END);
  65. FileSize = getPos();
  66. fseek(File, 0, SEEK_SET);
  67. }
  68. }
  69. //! returns name of file
  70. const io::path& CReadFile::getFileName() const
  71. {
  72. return Filename;
  73. }
  74. IReadFile* createReadFile(const io::path& fileName)
  75. {
  76. CReadFile* file = new CReadFile(fileName);
  77. if (file->isOpen())
  78. return file;
  79. file->drop();
  80. return 0;
  81. }
  82. } // end namespace io
  83. } // end namespace irr