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
26 void hreader_init(const char *path, struct hreader *h) {
27 memset(h, 0, sizeof *h);
28 h->path = xstrdup(path);
30 h->buffer = xmalloc_noptr(h->bufsize);
33 int hreader_read(struct hreader *h, void *buffer, size_t n) {
34 if(h->consumed == h->bytes) {
37 if((r = hreader_fill(h)) <= 0)
40 if(n > h->bytes - h->consumed)
41 n = h->bytes - h->consumed;
42 memcpy(buffer, h->buffer + h->consumed, n);
47 int hreader_fill(struct hreader *h) {
48 if(h->consumed < h->bytes)
49 return h->bytes - h->consumed;
50 h->bytes = h->consumed = 0;
51 int fd = open(h->path, O_RDONLY);
54 if(lseek(fd, h->offset, SEEK_SET) < 0) {
58 int n = read(fd, h->buffer, h->bufsize);
67 void hreader_consume(struct hreader *h, size_t n) {