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