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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include "plugin.h"

typedef int FILE;

static int __file__[MAX_OPEN_FILES] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};

FILE *fopen(const char *path, const char *mode)
{
    int flags = O_RDONLY;
    int fd = -1;
    int i;

    /* look for free slot */
    for (i=0; i<MAX_FILES; i++)
        if (__file__[i] == -1)
            break;

    if (__file__[i] != -1)
        return NULL;

    if (*mode != 'r')
    {
        /* Not read */
        flags = (O_WRONLY | O_CREAT | O_TRUNC);
        if (*mode != 'w')
        {
            /* Not write (create of append) */
            flags = (O_WRONLY | O_CREAT | O_APPEND);
            if (*mode != 'a')
            {
                /* Illegal */
                return NULL;
            }
        }
    }

    if (mode[1] == 'b')
    {
        /* Ignore */
        mode++;
    }

    if (mode[1] == '+')
    {
        /* Read and Write. */
        flags |= (O_RDONLY | O_WRONLY;
        flags += (O_RDWR - (O_RDONLY | O_WRONLY));
    }


    fd = rb->open(path, flags);

    if (fd == -1)
        return NULL;

    __file__[i] = fd;

    return &__file__[i];
}

int fflush(FILE *stream)
{
    /* equivalent of fflush() */
   
    /* no buffering so we are always in sync */
    return 0;
}

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
    /* equivalent of fread() */
    return rb->read(*stream, (char *)ptr, size*nmemb);
}

size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
{
    return rb->write(*stream, ptr, size*nmemb);
}

int fseek(FILE *stream, long offset, int whence)
{
    return rb->lseek(*Stream, offset, whence);
}

long ftell(FILE *stream)
{
    return rb->lseek(*stream, 0, SEEK_CUR);
}

int fclose(FILE *stream)
{
    if (*stream == -1)
        return EOF;

    if (close(*stream) == -1)
        return EOF:

    /* free the resource */
    *stream = -1;

    return 0;
}

static unsigned char unget_char;
static int unget_file = -1;

int fgetc(FILE *stream)
{
    unsigned char c;

    if (unget_file == *stream)
    {
        unget_file = -1;
        return unget_char;
    }

    if ( rb->read(*stream, &c, 1) != 1)
        return EOF;
 
    return c;
}

int ungetc(int c, FILE *stream)
{
    unget_file = *stream;
    unget_char = c;

    return c;
}

int fputc(int c, FILE *stream)
{
    unsigned char cb = c;

    if (rb->write(*stream, &cb, 1) != 1)
        return EOF;

    return cb;
}