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 static int hreader_fill(struct hreader
*h
, off_t offset
);
28 void hreader_init(const char *path
, struct hreader
*h
) {
29 memset(h
, 0, sizeof *h
);
30 h
->path
= xstrdup(path
);
32 h
->buffer
= xmalloc_noptr(h
->bufsize
);
35 int hreader_read(struct hreader
*h
, void *buffer
, size_t n
) {
36 int r
= hreader_pread(h
, buffer
, n
, h
->read_offset
);
42 int hreader_pread(struct hreader
*h
, void *buffer
, size_t n
, off_t offset
) {
43 size_t bytes_read
= 0;
45 while(bytes_read
< n
) {
46 // If the desired byte range is outside the file, fetch new contents
47 if(offset
< h
->buf_offset
|| offset
>= h
->buf_offset
+ (off_t
)h
->bytes
) {
48 int r
= hreader_fill(h
, offset
);
50 return -1; /* disaster! */
52 break; /* end of file */
54 // Figure out how much we can read this time round
55 size_t left
= h
->bytes
- (offset
- h
->buf_offset
);
56 // Truncate the read if we don't want that much
57 if(left
> (n
- bytes_read
))
58 left
= n
- bytes_read
;
59 memcpy((char *)buffer
+ bytes_read
,
60 h
->buffer
+ (offset
- h
->buf_offset
),
68 static int hreader_fill(struct hreader
*h
, off_t offset
) {
69 int fd
= open(h
->path
, O_RDONLY
);
72 int n
= pread(fd
, h
->buffer
, h
->bufsize
, offset
);
76 h
->buf_offset
= offset
;