2 * This file is part of DisOrder
3 * Copyright (C) 2010 Richard Kettlewell
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 /** @file lib/hreader.c
19 * @brief Hands-off reader - read files without keeping them open
30 static int hreader_fill(struct hreader *h, off_t offset);
32 int hreader_init(const char *path, struct hreader *h) {
34 if(stat(path, &sb) < 0)
36 memset(h, 0, sizeof *h);
37 h->path = xstrdup(path);
40 h->buffer = xmalloc_noptr(h->bufsize);
44 void hreader_close(struct hreader *h) {
49 int hreader_read(struct hreader *h, void *buffer, size_t n) {
50 int r = hreader_pread(h, buffer, n, h->read_offset);
56 int hreader_pread(struct hreader *h, void *buffer, size_t n, off_t offset) {
57 size_t bytes_read = 0;
59 while(bytes_read < n) {
60 // If the desired byte range is outside the file, fetch new contents
61 if(offset < h->buf_offset || offset >= h->buf_offset + (off_t)h->bytes) {
62 int r = hreader_fill(h, offset);
64 return -1; /* disaster! */
66 break; /* end of file */
68 // Figure out how much we can read this time round
69 size_t left = h->bytes - (offset - h->buf_offset);
70 // Truncate the read if we don't want that much
71 if(left > (n - bytes_read))
72 left = n - bytes_read;
73 memcpy((char *)buffer + bytes_read,
74 h->buffer + (offset - h->buf_offset),
82 static int hreader_fill(struct hreader *h, off_t offset) {
83 int fd = open(h->path, O_RDONLY);
86 int n = pread(fd, h->buffer, h->bufsize, offset);
90 h->buf_offset = offset;
95 off_t hreader_seek(struct hreader *h, off_t offset, int whence) {
98 case SEEK_CUR: offset += h->read_offset; break;
99 case SEEK_END: offset += h->size; break;
100 default: einval: errno = EINVAL; return -1;
102 if(offset < 0) goto einval;
103 h->read_offset = offset;