#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;
}