1 /* 2 * Copyright 2009-2010, Ingo Weinhold, ingo_weinhold@gmx.de. 3 * Distributed under the terms of the MIT License. 4 */ 5 6 7 #include <FileDescriptorIO.h> 8 9 #include <errno.h> 10 #include <stdio.h> 11 #include <sys/stat.h> 12 #include <unistd.h> 13 14 15 BFileDescriptorIO::BFileDescriptorIO(int fd, bool takeOverOwnership) 16 : 17 fFD(fd), 18 fOwnsFD(takeOverOwnership) 19 { 20 } 21 22 23 BFileDescriptorIO::~BFileDescriptorIO() 24 { 25 if (fOwnsFD) 26 close(fFD); 27 } 28 29 30 ssize_t 31 BFileDescriptorIO::Read(void* buffer, size_t size) 32 { 33 ssize_t bytesRead = read(fFD, buffer, size); 34 return bytesRead >= 0 ? bytesRead : errno; 35 } 36 37 38 ssize_t 39 BFileDescriptorIO::Write(const void* buffer, size_t size) 40 { 41 ssize_t bytesWritten = write(fFD, buffer, size); 42 return bytesWritten >= 0 ? bytesWritten : errno; 43 } 44 45 46 ssize_t 47 BFileDescriptorIO::ReadAt(off_t position, void* buffer, size_t size) 48 { 49 ssize_t bytesRead = pread(fFD, buffer, size, position); 50 return bytesRead >= 0 ? bytesRead : errno; 51 } 52 53 54 ssize_t 55 BFileDescriptorIO::WriteAt(off_t position, const void* buffer, size_t size) 56 { 57 ssize_t bytesWritten = pwrite(fFD, buffer, size, position); 58 return bytesWritten >= 0 ? bytesWritten : errno; 59 } 60 61 62 off_t 63 BFileDescriptorIO::Seek(off_t position, uint32 seekMode) 64 { 65 off_t result = lseek(fFD, position, seekMode); 66 return result >= 0 ? result : errno; 67 } 68 69 70 off_t 71 BFileDescriptorIO::Position() const 72 { 73 off_t result = lseek(fFD, 0, SEEK_CUR); 74 return result >= 0 ? result : errno; 75 } 76 77 78 status_t 79 BFileDescriptorIO::SetSize(off_t size) 80 { 81 return ftruncate(fFD, size) == 0 ? B_OK : errno; 82 } 83 84 85 status_t 86 BFileDescriptorIO::GetSize(off_t* size) const 87 { 88 struct stat st; 89 if (fstat(fFD, &st) < 0) 90 return errno; 91 92 *size = st.st_size; 93 return B_OK; 94 } 95