repository_infos: Enable automatic updates on the main Haiku repostiory.
[haiku.git] / src / kits / storage / FileIO.cpp
blob439f836ab068fd13b211e59273523aa4e0be9b23
1 /*
2 * Copyright 2009-2010, Ingo Weinhold, ingo_weinhold@gmx.de.
3 * Distributed under the terms of the MIT License.
4 */
7 #include <FileIO.h>
9 #include <errno.h>
10 #include <stdio.h>
13 BFileIO::BFileIO(FILE* file, bool takeOverOwnership)
15 fFile(file),
16 fOwnsFile(takeOverOwnership)
21 BFileIO::~BFileIO()
23 if (fOwnsFile && fFile != NULL)
24 fclose(fFile);
28 ssize_t
29 BFileIO::Read(void* buffer, size_t size)
31 errno = B_OK;
32 ssize_t bytesRead = fread(buffer, 1, size, fFile);
33 return bytesRead >= 0 ? bytesRead : errno;
37 ssize_t
38 BFileIO::Write(const void* buffer, size_t size)
40 errno = B_OK;
41 ssize_t bytesRead = fwrite(buffer, 1, size, fFile);
42 return bytesRead >= 0 ? bytesRead : errno;
46 ssize_t
47 BFileIO::ReadAt(off_t position, void* buffer, size_t size)
49 // save the old position and seek to the requested one
50 off_t oldPosition = _Seek(position, SEEK_SET);
51 if (oldPosition < 0)
52 return oldPosition;
54 // read
55 ssize_t result = BFileIO::Read(buffer, size);
57 // seek back
58 fseeko(fFile, oldPosition, SEEK_SET);
60 return result;
64 ssize_t
65 BFileIO::WriteAt(off_t position, const void* buffer, size_t size)
67 // save the old position and seek to the requested one
68 off_t oldPosition = _Seek(position, SEEK_SET);
69 if (oldPosition < 0)
70 return oldPosition;
72 // write
73 ssize_t result = BFileIO::Write(buffer, size);
75 // seek back
76 fseeko(fFile, oldPosition, SEEK_SET);
78 return result;
82 off_t
83 BFileIO::Seek(off_t position, uint32 seekMode)
85 if (fseeko(fFile, position, seekMode) < 0)
86 return errno;
88 return BFileIO::Position();
92 off_t
93 BFileIO::Position() const
95 off_t result = ftello(fFile);
96 return result >= 0 ? result : errno;
100 status_t
101 BFileIO::SetSize(off_t size)
103 return B_UNSUPPORTED;
107 status_t
108 BFileIO::GetSize(off_t* _size) const
110 // save the current position and seek to the end
111 off_t position = _Seek(0, SEEK_END);
112 if (position < 0)
113 return position;
115 // get the size (position at end) and seek back
116 off_t size = _Seek(position, SEEK_SET);
117 if (size < 0)
118 return size;
120 *_size = size;
121 return B_OK;
125 off_t
126 BFileIO::_Seek(off_t position, uint32 seekMode) const
128 // save the current position
129 off_t oldPosition = ftello(fFile);
130 if (oldPosition < 0)
131 return errno;
133 // seek to the requested position
134 if (fseeko(fFile, position, seekMode) < 0)
135 return errno;
137 return oldPosition;