xref: /haiku/src/kits/storage/FdIO.cpp (revision 21258e2674226d6aa732321b6f8494841895af5f)
1 /*
2  * Copyright 2014, Ingo Weinhold, ingo_weinhold@gmx.de.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 
7 #include <FdIO.h>
8 
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <unistd.h>
12 
13 
14 BFdIO::BFdIO()
15 	:
16 	BPositionIO(),
17 	fFd(-1),
18 	fOwnsFd(false)
19 {
20 }
21 
22 
23 BFdIO::BFdIO(int fd, bool keepFd)
24 	:
25 	BPositionIO(),
26 	fFd(fd),
27 	fOwnsFd(keepFd)
28 {
29 }
30 
31 
32 BFdIO::~BFdIO()
33 {
34 	Unset();
35 }
36 
37 
38 void
39 BFdIO::SetTo(int fd, bool keepFd)
40 {
41 	Unset();
42 
43 	fFd = fd;
44 	fOwnsFd = keepFd;
45 }
46 
47 
48 void
49 BFdIO::Unset()
50 {
51 	if (fOwnsFd && fFd >= 0)
52 		close(fFd);
53 
54 	fFd = -1;
55 	fOwnsFd = false;
56 }
57 
58 
59 ssize_t
60 BFdIO::Read(void* buffer, size_t size)
61 {
62 	ssize_t bytesRead = read(fFd, buffer, size);
63 	return bytesRead >= 0 ? bytesRead : errno;
64 }
65 
66 
67 ssize_t
68 BFdIO::Write(const void* buffer, size_t size)
69 {
70 	ssize_t bytesWritten = write(fFd, buffer, size);
71 	return bytesWritten >= 0 ? bytesWritten : errno;
72 }
73 
74 
75 ssize_t
76 BFdIO::ReadAt(off_t position, void* buffer, size_t size)
77 {
78 	ssize_t bytesRead = pread(fFd, buffer, size, position);
79 	return bytesRead >= 0 ? bytesRead : errno;
80 }
81 
82 
83 ssize_t
84 BFdIO::WriteAt(off_t position, const void* buffer, size_t size)
85 {
86 	ssize_t bytesWritten = pwrite(fFd, buffer, size, position);
87 	return bytesWritten >= 0 ? bytesWritten : errno;
88 }
89 
90 
91 off_t
92 BFdIO::Seek(off_t position, uint32 seekMode)
93 {
94 	off_t newPosition = lseek(fFd, position, seekMode);
95 	return newPosition >= 0 ? newPosition : errno;
96 }
97 
98 
99 off_t
100 BFdIO::Position() const
101 {
102 	return const_cast<BFdIO*>(this)->BFdIO::Seek(0, SEEK_CUR);
103 }
104 
105 
106 status_t
107 BFdIO::SetSize(off_t size)
108 {
109 	return ftruncate(fFd, size) == 0 ? B_OK : errno;
110 }
111 
112 
113 status_t
114 BFdIO::GetSize(off_t* _size) const
115 {
116 	struct stat st;
117 	if (fstat(fFd, &st) != 0)
118 		return errno;
119 
120 	*_size = st.st_size;
121 	return B_OK;
122 }
123