libdebugger: Add initial version of network interface.
[haiku.git] / src / kits / storage / FdIO.cpp
blob19e83b3f295ffed3ffb88fab13b982abddcceab6
1 /*
2 * Copyright 2014, Ingo Weinhold, ingo_weinhold@gmx.de.
3 * Distributed under the terms of the MIT License.
4 */
7 #include <FdIO.h>
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <unistd.h>
14 BFdIO::BFdIO()
16 BPositionIO(),
17 fFd(-1),
18 fOwnsFd(false)
23 BFdIO::BFdIO(int fd, bool keepFd)
25 BPositionIO(),
26 fFd(fd),
27 fOwnsFd(keepFd)
32 BFdIO::~BFdIO()
34 Unset();
38 void
39 BFdIO::SetTo(int fd, bool keepFd)
41 Unset();
43 fFd = fd;
44 fOwnsFd = keepFd;
48 void
49 BFdIO::Unset()
51 if (fOwnsFd && fFd >= 0)
52 close(fFd);
54 fFd = -1;
55 fOwnsFd = false;
59 ssize_t
60 BFdIO::Read(void* buffer, size_t size)
62 ssize_t bytesRead = read(fFd, buffer, size);
63 return bytesRead >= 0 ? bytesRead : errno;
67 ssize_t
68 BFdIO::Write(const void* buffer, size_t size)
70 ssize_t bytesWritten = write(fFd, buffer, size);
71 return bytesWritten >= 0 ? bytesWritten : errno;
75 ssize_t
76 BFdIO::ReadAt(off_t position, void* buffer, size_t size)
78 ssize_t bytesRead = pread(fFd, buffer, size, position);
79 return bytesRead >= 0 ? bytesRead : errno;
83 ssize_t
84 BFdIO::WriteAt(off_t position, const void* buffer, size_t size)
86 ssize_t bytesWritten = pwrite(fFd, buffer, size, position);
87 return bytesWritten >= 0 ? bytesWritten : errno;
91 off_t
92 BFdIO::Seek(off_t position, uint32 seekMode)
94 off_t newPosition = lseek(fFd, position, seekMode);
95 return newPosition >= 0 ? newPosition : errno;
99 off_t
100 BFdIO::Position() const
102 return const_cast<BFdIO*>(this)->BFdIO::Seek(0, SEEK_CUR);
106 status_t
107 BFdIO::SetSize(off_t size)
109 return ftruncate(fFd, size) == 0 ? B_OK : errno;
113 status_t
114 BFdIO::GetSize(off_t* _size) const
116 struct stat st;
117 if (fstat(fFd, &st) != 0)
118 return errno;
120 *_size = st.st_size;
121 return B_OK;