]> git.draconx.ca Git - liblbx.git/blob - src/lbx.c
Initial commit
[liblbx.git] / src / lbx.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdint.h>
4
5 #include "byteorder.h"
6 #include "lbx.h"
7
8 #define LBX_MAGIC 0x0000fead
9
10 struct lbx_state {
11         FILE *f;
12         uint16_t nfiles;
13         uint32_t offsets[];
14 };
15
16 struct lbx_state *lbx_fopen(FILE *f)
17 {
18         struct lbx_state *new = NULL;
19         uint16_t nfiles, version;
20         uint32_t magic;
21
22         if (fread(&nfiles,  sizeof nfiles,  1, f) != 1) return NULL;
23         if (fread(&magic,   sizeof magic,   1, f) != 1) return NULL;
24         if (fread(&version, sizeof version, 1, f) != 1) return NULL;
25
26         nfiles  = letohs(nfiles);
27         magic   = letohl(magic);
28         version = letohs(version);
29
30         if (magic != LBX_MAGIC)
31                 return NULL;
32         
33         new = malloc(sizeof *new + (nfiles+1)*(sizeof *new->offsets));
34         if (!new)
35                 return NULL;
36         
37         *new = (struct lbx_state){
38                 .nfiles = nfiles,
39                 .f = f,
40         };
41         
42         if (fread(new->offsets, sizeof *new->offsets, nfiles+1, f) != nfiles+1)
43                 return free(new), NULL;
44
45         return new;
46 }
47
48 struct lbx_state *lbx_open(const char *path)
49 {
50         struct lbx_state *new = NULL;
51         FILE *f;
52         
53         if ((f = fopen(path, "rb")))
54                 new = lbx_fopen(f);
55
56         return new;
57 }
58
59 void lbx_close(struct lbx_state *lbx)
60 {
61         fclose(lbx->f);
62         free(lbx);
63 }