1
2 /*
3 * io_file.c
4 *
5 * Implements the file interface.
6 *
7 * As will all I/O modules, most functions are for local use only (called
8 * via function pointers in the I/O context).
9 *
10 * Most functions are just 'wrappers' for standard file functions.
11 *
12 * Written/Modified 1999, Philip Warner.
13 *
14 */
15
16 /* For platforms with incomplete ANSI defines. Fortunately,
17 SEEK_SET is defined to be zero by the standard. */
18
19 #ifndef SEEK_SET
20 #define SEEK_SET 0
21 #endif /* SEEK_SET */
22
23 #include <math.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include "gd.h"
27 #include "gdhelpers.h"
28
29 /* this is used for creating images in main memory */
30
31 typedef struct fileIOCtx
32 {
33 gdIOCtx ctx;
34 FILE *f;
35 } fileIOCtx;
36
37 gdIOCtx *newFileCtx (FILE * f);
38
39 static int fileGetbuf (gdIOCtx *, void *, int);
40 static int filePutbuf (gdIOCtx *, const void *, int);
41 static void filePutchar (gdIOCtx *, int);
42 static int fileGetchar (gdIOCtx * ctx);
43
44 static int fileSeek (struct gdIOCtx *, const int);
45 static long fileTell (struct gdIOCtx *);
46 static void gdFreeFileCtx (gdIOCtx * ctx);
47
48 /* return data as a dynamic pointer */
gdNewFileCtx(FILE * f)49 gdIOCtx * gdNewFileCtx (FILE * f)
50 {
51 fileIOCtx *ctx;
52
53 ctx = (fileIOCtx *) gdMalloc(sizeof (fileIOCtx));
54
55 ctx->f = f;
56
57 ctx->ctx.getC = fileGetchar;
58 ctx->ctx.putC = filePutchar;
59
60 ctx->ctx.getBuf = fileGetbuf;
61 ctx->ctx.putBuf = filePutbuf;
62
63 ctx->ctx.tell = fileTell;
64 ctx->ctx.seek = fileSeek;
65
66 ctx->ctx.gd_free = gdFreeFileCtx;
67
68 return (gdIOCtx *) ctx;
69 }
70
gdFreeFileCtx(gdIOCtx * ctx)71 static void gdFreeFileCtx (gdIOCtx * ctx)
72 {
73 gdFree(ctx);
74 }
75
76
filePutbuf(gdIOCtx * ctx,const void * buf,int size)77 static int filePutbuf (gdIOCtx * ctx, const void *buf, int size)
78 {
79 fileIOCtx *fctx;
80 fctx = (fileIOCtx *) ctx;
81
82 return fwrite(buf, 1, size, fctx->f);
83
84 }
85
fileGetbuf(gdIOCtx * ctx,void * buf,int size)86 static int fileGetbuf (gdIOCtx * ctx, void *buf, int size)
87 {
88 fileIOCtx *fctx;
89 fctx = (fileIOCtx *) ctx;
90
91 return fread(buf, 1, size, fctx->f);
92 }
93
filePutchar(gdIOCtx * ctx,int a)94 static void filePutchar (gdIOCtx * ctx, int a)
95 {
96 unsigned char b;
97 fileIOCtx *fctx;
98 fctx = (fileIOCtx *) ctx;
99
100 b = a;
101
102 putc (b, fctx->f);
103 }
104
fileGetchar(gdIOCtx * ctx)105 static int fileGetchar (gdIOCtx * ctx)
106 {
107 fileIOCtx *fctx;
108 fctx = (fileIOCtx *) ctx;
109
110 return getc (fctx->f);
111 }
112
113
fileSeek(struct gdIOCtx * ctx,const int pos)114 static int fileSeek (struct gdIOCtx *ctx, const int pos)
115 {
116 fileIOCtx *fctx;
117 fctx = (fileIOCtx *) ctx;
118
119 return (fseek (fctx->f, pos, SEEK_SET) == 0);
120 }
121
fileTell(struct gdIOCtx * ctx)122 static long fileTell (struct gdIOCtx *ctx)
123 {
124 fileIOCtx *fctx;
125 fctx = (fileIOCtx *) ctx;
126
127 return ftell (fctx->f);
128 }
129