-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfmemopen.c
executable file
·78 lines (63 loc) · 1.67 KB
/
fmemopen.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
* fmem.c : fmemopen() on top of BSD's funopen()
* 20081017 AF
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef linux
struct fmem {
size_t pos;
size_t size;
char *buffer;
};
typedef struct fmem fmem_t;
static int readfn(void *handler, char *buf, int size)
{
int count = 0;
fmem_t *mem = handler;
size_t available = mem->size - mem->pos;
if(size > available) size = available;
for(count=0; count < size; mem->pos++, count++)
buf[count] = mem->buffer[mem->pos];
return count;
}
static int writefn(void *handler, const char *buf, int size)
{
int count = 0;
fmem_t *mem = handler;
size_t available = mem->size - mem->pos;
if(size > available) size = available;
for(count=0; count < size; mem->pos++, count++)
mem->buffer[mem->pos] = buf[count];
return count; // ? count : size;
}
static fpos_t seekfn(void *handler, fpos_t offset, int whence)
{
size_t pos;
fmem_t *mem = handler;
switch(whence) {
case SEEK_SET: pos = offset; break;
case SEEK_CUR: pos = mem->pos + offset; break;
case SEEK_END: pos = mem->size + offset; break;
default: return -1;
}
if(pos < 0 || pos > mem->size) return -1;
mem->pos = pos;
return (fpos_t) pos;
}
static int closefn(void *handler)
{
free(handler);
return 0;
}
/* simple, but portable version of fmemopen for OS X / BSD */
FILE *fmemopen(void *buf, size_t size, const char *mode)
{
fmem_t *mem = (fmem_t *) malloc(sizeof(fmem_t));
memset(mem, 0, sizeof(fmem_t));
mem->size = size, mem->buffer = buf;
return funopen(mem, readfn, writefn, seekfn, closefn);
}
#endif