C_FileIO.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Common/C_FileIO.h
  2. #include "C_FileIO.h"
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. namespace NC {
  6. namespace NFile {
  7. namespace NIO {
  8. bool CFileBase::OpenBinary(const char *name, int flags)
  9. {
  10. #ifdef O_BINARY
  11. flags |= O_BINARY;
  12. #endif
  13. Close();
  14. _handle = ::open(name, flags, 0666);
  15. return _handle != -1;
  16. }
  17. bool CFileBase::Close()
  18. {
  19. if(_handle == -1)
  20. return true;
  21. if (close(_handle) != 0)
  22. return false;
  23. _handle = -1;
  24. return true;
  25. }
  26. bool CFileBase::GetLength(UInt64 &length) const
  27. {
  28. off_t curPos = Seek(0, SEEK_CUR);
  29. off_t lengthTemp = Seek(0, SEEK_END);
  30. Seek(curPos, SEEK_SET);
  31. length = (UInt64)lengthTemp;
  32. return true;
  33. }
  34. off_t CFileBase::Seek(off_t distanceToMove, int moveMethod) const
  35. {
  36. return ::lseek(_handle, distanceToMove, moveMethod);
  37. }
  38. /////////////////////////
  39. // CInFile
  40. bool CInFile::Open(const char *name)
  41. {
  42. return CFileBase::OpenBinary(name, O_RDONLY);
  43. }
  44. bool CInFile::OpenShared(const char *name, bool)
  45. {
  46. return Open(name);
  47. }
  48. ssize_t CInFile::Read(void *data, size_t size)
  49. {
  50. return read(_handle, data, size);
  51. }
  52. /////////////////////////
  53. // COutFile
  54. bool COutFile::Create(const char *name, bool createAlways)
  55. {
  56. if (createAlways)
  57. {
  58. Close();
  59. _handle = ::creat(name, 0666);
  60. return _handle != -1;
  61. }
  62. return OpenBinary(name, O_CREAT | O_EXCL | O_WRONLY);
  63. }
  64. bool COutFile::Open(const char *name, DWORD creationDisposition)
  65. {
  66. return Create(name, false);
  67. }
  68. ssize_t COutFile::Write(const void *data, size_t size)
  69. {
  70. return write(_handle, data, size);
  71. }
  72. }}}