* Allows files to be read without holding them open.
*/
struct hreader {
- const char *path; /* file to read */
- off_t offset; /* how far we've read so far */
+ char *path; /* file to read */
+ off_t size; /* file size */
+ off_t read_offset; /* for next hreader_read() */
+ off_t buf_offset; /* offset of start of buffer */
char *buffer; /* input buffer */
size_t bufsize; /* buffer size */
size_t bytes; /* size of last read */
- size_t consumed; /* bytes consumed by caller from last read */
};
/** @brief Initialize a hands-off reader
* @param path File to read
* @param h Reader to initialize
+ * @return 0 on success, -1 on error
*/
-void hreader_init(const char *path, struct hreader *h);
+int hreader_init(const char *path, struct hreader *h);
+
+/** @brief Close a hands-off reader
+ * @param h Reader to close
+ */
+void hreader_close(struct hreader *h);
/** @brief Read some bytes
* @param h Reader to read from
*/
int hreader_read(struct hreader *h, void *buffer, size_t n);
-/** @brief Read more bytes
- * @param h Reader to update
- * @return Bytes available to read
- *
- * If not all bytes were consumed so far then just returns the number
- * of bytes left to consume.
+/** @brief Read some bytes at a given offset
+ * @param h Reader to read from
+ * @param offset Offset to read at
+ * @param buffer Where to store bytes
+ * @param n Maximum bytes to read
+ * @return Bytes read, or 0 at EOF, or -1 on error
+ */
+int hreader_pread(struct hreader *h, void *buffer, size_t n, off_t offset);
+
+/** @brief Seek within a file
+ * @param h Reader to seek
+ * @param offset Offset
+ * @param whence SEEK_*
+ * @return Result offset
*/
-int hreader_fill(struct hreader *h);
+off_t hreader_seek(struct hreader *h, off_t offset, int whence);
-/** @brief Consume some bytes
- * @param h Reader to update
- * @param n Bytes to consume
+/** @brief Return file size
+ * @param h Reader to find size of
+ * @return Size in bytes
+ */
+static inline off_t hreader_size(const struct hreader *h) {
+ return h->size;
+}
+
+/** @brief Test for end of file
+ * @param h Reader to test
+ * @return 1 at eof, 0 otherwise
+ *
+ * This tells you whether the next read will return 0 bytes, rather than
+ * whether the last read reached end of file. So it is slightly different to
+ * feof().
*/
-void hreader_consume(struct hreader *h, size_t n);
+static inline int hreader_eof(const struct hreader *h) {
+ return h->read_offset == h->size;
+}
#endif /* HREADER_H */