DEADSOFTWARE

map: use streams for map loader
[flatwaifu.git] / src / common / files.c
1 #include "files.h"
3 #include <stdio.h>
4 #include <stdint.h>
5 #include <assert.h>
7 static long FILE_Reader_GetPos (Reader *r) {
8 FILE_Reader *rd = (FILE_Reader*)r;
9 assert(rd != NULL);
10 assert(rd->fp != NULL);
11 long pos = ftell(rd->fp);
12 assert(pos != -1); // fail
13 return pos;
14 }
16 static void FILE_Reader_SetPos (Reader *r, long pos) {
17 FILE_Reader *rd = (FILE_Reader*)r;
18 assert(rd != NULL);
19 assert(rd->fp != NULL);
20 assert(pos >= 0);
21 int res = fseek(rd->fp, pos, SEEK_SET);
22 assert(res == 0); // fail
23 }
25 static void FILE_Reader_Read (Reader *r, void *data, size_t size, size_t n) {
26 FILE_Reader *rd = (FILE_Reader*)r;
27 assert(rd != NULL);
28 assert(rd->fp != NULL);
29 size_t res = fread(data, size, n, rd->fp);
30 assert(res == n); // fail
31 }
33 void FILE_AssignReader (FILE_Reader *r, FILE *fp) {
34 assert(r != NULL);
35 assert(fp != NULL);
36 r->base.getpos = FILE_Reader_GetPos;
37 r->base.setpos = FILE_Reader_SetPos;
38 r->base.read = FILE_Reader_Read;
39 r->fp = fp;
40 }
42 int FILE_OpenReader (FILE_Reader *r, const char *name) {
43 assert(r != NULL);
44 assert(name != NULL);
45 FILE *fp = fopen(name, "rb");
46 if (fp) {
47 FILE_AssignReader(r, fp);
48 }
49 return fp != NULL;
50 }
52 void FILE_CloseReader (FILE_Reader *r) {
53 assert(r != NULL);
54 if (r->fp != NULL) {
55 fclose(r->fp);
56 }
57 r->base.getpos = NULL;
58 r->base.setpos = NULL;
59 r->base.read = NULL;
60 r->fp = NULL;
61 }
63 static long FILE_Writer_GetPos (Writer *w) {
64 FILE_Writer *wr = (FILE_Writer*)w;
65 assert(wr != NULL);
66 assert(wr->fp != NULL);
67 long pos = ftell(wr->fp);
68 assert(pos != -1); // fail
69 return pos;
70 }
72 static void FILE_Writer_SetPos (Writer *w, long pos) {
73 FILE_Writer *wr = (FILE_Writer*)w;
74 assert(wr != NULL);
75 assert(wr->fp != NULL);
76 assert(pos >= 0);
77 int res = fseek(wr->fp, pos, SEEK_SET);
78 assert(res == 0); // fail
79 }
81 static void FILE_Writer_Write (Writer *w, const void *data, size_t size, size_t n) {
82 FILE_Writer *wr = (FILE_Writer*)w;
83 assert(wr != NULL);
84 assert(wr->fp != NULL);
85 size_t res = fwrite(data, size, n, wr->fp);
86 assert(res == n); // fail
87 }
89 void FILE_AssignWriter (FILE_Writer *w, FILE *fp) {
90 assert(w != NULL);
91 assert(fp != NULL);
92 w->base.getpos = FILE_Writer_GetPos;
93 w->base.setpos = FILE_Writer_SetPos;
94 w->base.write = FILE_Writer_Write;
95 w->fp = fp;
96 }
98 int FILE_OpenWriter (FILE_Writer *w, const char *name) {
99 assert(w != NULL);
100 assert(name != NULL);
101 FILE *fp = fopen(name, "wb");
102 if (fp) {
103 FILE_AssignWriter(w, fp);
105 return fp != NULL;
108 void FILE_CloseWriter (FILE_Writer *w) {
109 assert(w != NULL);
110 if (w->fp != NULL) {
111 fclose(w->fp);
113 w->base.getpos = NULL;
114 w->base.setpos = NULL;
115 w->base.write = NULL;
116 w->fp = NULL;