+int lbx_stat(struct lbx_state *lbx, size_t index, struct lbx_statbuf *buf)
+{
+ static char str[256]; /* FIXME */
+
+ if (index >= lbx->nfiles) {
+ buf->name = NULL;
+ lbx_errno = LBX_ERANGE;
+ return -1;
+ }
+
+ snprintf(str, sizeof str, "%s.%03d", lbx->name, index);
+ buf->name = str;
+ buf->size = lbx->offsets[index+1] - lbx->offsets[index];
+ return 0;
+}
+
+/*
+ * Read and discard len bytes from the file. On success, returns 0. On
+ * failure, returns -1 and sets lbx_errno.
+ */
+static int skipdata(FILE *f, size_t len)
+{
+ unsigned char buf[1024];
+
+ while (len) {
+ if (fread(buf, MIN(sizeof buf, len), 1, f) != 1) {
+ if (feof(f)) {
+ lbx_errno = LBX_EEOF;
+ } else {
+ lbx_errno = -errno;
+ }
+ return -1;
+ }
+ len -= MIN(sizeof buf, len);
+ }
+
+ return 0;
+}
+
+size_t lbx_extract(struct lbx_state *lbx, size_t index, FILE *of)
+{
+ unsigned char buf[1024];
+ size_t rc, written = 0, base, len;
+
+ if (index >= lbx->nfiles) {
+ lbx_errno = LBX_ERANGE;
+ return 0;
+ }
+
+ base = lbx->offsets[index];
+ len = lbx->offsets[index+1] - lbx->offsets[index];
+
+ /* Seek to the beginning of the file. */
+ if (lbx->foff != base) {
+ int seekrc;
+ long dist = (lbx->foff < base) ? (base - lbx->foff)
+ : -(lbx->foff - base);
+
+ seekrc = fseek(lbx->f, dist, SEEK_CUR);
+ if (seekrc == -1 && lbx->foff < base) {
+ if (skipdata(lbx->f, dist) == -1) {
+ /* lbx_errno set by skipdata */
+ return 0;
+ }
+ } else if (seekrc == -1) {
+ lbx_errno = -errno;
+ return 0;
+ }
+ lbx->foff += dist; /* FIXME: failed skipdata breaks this. */
+ }
+
+ /* Copy file data */
+ while (len) {
+ size_t amt = MIN(sizeof buf, len);
+
+ rc = fread(buf, 1, amt, lbx->f);
+ lbx->foff += rc;
+ len -= rc;
+ if (rc < amt) {
+ if (feof(lbx->f)) {
+ lbx_errno = LBX_EEOF;
+ } else {
+ lbx_errno = -errno;
+ }
+ break;
+ }
+
+ rc = fwrite(buf, 1, amt, of);
+ written += rc;
+ if (rc < amt) {
+ lbx_errno = -errno;
+ break;
+ }
+ }
+
+ return written;
+}
+