CWriteFile.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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 "CWriteFile.h"
  5. #include <stdio.h>
  6. namespace irr
  7. {
  8. namespace io
  9. {
  10. CWriteFile::CWriteFile(const io::path& fileName, bool append)
  11. : FileSize(0)
  12. {
  13. #ifdef _DEBUG
  14. setDebugName("CWriteFile");
  15. #endif
  16. Filename = fileName;
  17. openFile(append);
  18. }
  19. CWriteFile::~CWriteFile()
  20. {
  21. if (File)
  22. fclose(File);
  23. }
  24. //! returns if file is open
  25. inline bool CWriteFile::isOpen() const
  26. {
  27. return File != 0;
  28. }
  29. //! returns how much was read
  30. s32 CWriteFile::write(const void* buffer, u32 sizeToWrite)
  31. {
  32. if (!isOpen())
  33. return 0;
  34. return (s32)fwrite(buffer, 1, sizeToWrite, File);
  35. }
  36. //! changes position in file, returns true if successful
  37. //! if relativeMovement==true, the pos is changed relative to current pos,
  38. //! otherwise from begin of file
  39. bool CWriteFile::seek(long finalPos, bool relativeMovement)
  40. {
  41. if (!isOpen())
  42. return false;
  43. return fseek(File, finalPos, relativeMovement ? SEEK_CUR : SEEK_SET) == 0;
  44. }
  45. //! returns where in the file we are.
  46. long CWriteFile::getPos() const
  47. {
  48. return ftell(File);
  49. }
  50. //! opens the file
  51. void CWriteFile::openFile(bool append)
  52. {
  53. if (Filename.size() == 0)
  54. {
  55. File = 0;
  56. return;
  57. }
  58. #if defined(_IRR_WCHAR_FILESYSTEM)
  59. File = _wfopen(Filename.c_str(), append ? L"ab" : L"wb");
  60. #else
  61. File = fopen(Filename.c_str(), append ? "ab" : "wb");
  62. #endif
  63. if (File)
  64. {
  65. // get FileSize
  66. fseek(File, 0, SEEK_END);
  67. FileSize = ftell(File);
  68. fseek(File, 0, SEEK_SET);
  69. }
  70. }
  71. //! returns name of file
  72. const io::path& CWriteFile::getFileName() const
  73. {
  74. return Filename;
  75. }
  76. IWriteFile* createWriteFile(const io::path& fileName, bool append)
  77. {
  78. CWriteFile* file = new CWriteFile(fileName, append);
  79. if (file->isOpen())
  80. return file;
  81. file->drop();
  82. return 0;
  83. }
  84. } // end namespace io
  85. } // end namespace irr