
Opening a FILE * on a buffer
Quote:
> I have a server process which recieves a message from the client via a
> socket. The middleware yields a memory buffer which the server is then
free
> to parse. I'd like to use fgets(), fgetw(), fgetc(), fputc(), to parse
the
> message in predictable ways. I could write my own functions for
emulating
> f*()'s behavior but I was hoping to use a trick that had already been
> discovered. The more portable the better...
You can't use FILE * to open a memory buffer, and there's very little point
in doing it anyway. But you could use a char * in place of a FILE * to
cover most of it.
I'd do it by defining a new type, an instance of which carries around a
pointer to the data buffer, a size, and a "current byte" indicator, either
a size_t or a pointer. Then pass this thing around to your imitative
functions in the usual way.
example, using Buffer instead of File:
#include <stdio.h>
typedef struct BILE
{
char *buffer;
size_t size;
size_t current;
Quote:
} BILE;
BILE *ropen(char *s, size_t len)
{
BILE *b = malloc(sizeof *b);
if(b != NULL)
{
b->buffer = s;
b->size = len;
b->current = 0;
}
return b;
Quote:
}
void bclose(BILE *b)
{
free(b);
Quote:
}
Now bgetc, for example, is pretty trivial:
int bgetc(BILE *b)
{
int i;
if(size > current + 1)
{
i = buffer[current++];
}
else
{
i = EOF;
}
return i;
Quote:
}
bgets() and so on are really quite simple too (hint: look in K&R). But
really, we're just playing games with the language. Are you SURE you want
to do this?
--
Richard Heathfield
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
--