也许您可以稍微更改代码以接收自定义句柄。
void parse(my_handle *h, Element *result)
{
// read from handle and process
// call h->read instead of fread
}
并像这样定义句柄:
struct my_handle
{
// wrapper for fread or something
int (*read)(struct my_handle *h, char *buffer, int readsize);
// maybe some more methods you need
};
实现你的 FILE* 包装器
struct my_file_handle
{
struct my_handle base;
FILE *fp;
};
int read_from_file(struct my_handle *h, char *buffer, int readsize)
{
return fread(buffer, 1, readsize, ((my_file_handle*)h)->fp);
}
// function to init the FILE* wrapper
void init_my_file_handle(struct my_file_handle *h, FILE *fp)
{
h->base.read = read_from_file;
h->fp = fp;
}
现在,实现你的字符串阅读器
struct my_string_handle
{
struct my_handle base;
// string buffer, size, and current position
const char *buffer;
int size;
int position;
};
// string reader
int read_from_string(struct my_handle *h, char *buffer, int readsize)
{
// implement it yourself. It's easy.
}
// create string reader handle
void init_my_string_handle(struct my_string_handle *h, const char *str, int strsize)
{
// i think you know how to init it now.
}
/////////////////////////////////////////
现在,您可以简单地向您的解析函数发送一个句柄。该函数不关心数据来自哪里,它甚至可以从网络中读取数据!