一个在C中使用FILE和char*的读取器接口



我正在修改我继承的一个解析器,该解析器目前仅通过读取从FILE*读取。现在,它还需要能够从char*常量中提取数据,以便可以解析C字符串中的内联文本。

我已经考虑过以"阅读器"的形式为两者提供一个简单的接口,这样您就可以提供一个文件阅读器和一个字符阅读器,解析器可以从中获取字符。例如:

// Inputs
const char *str = "stringToParse";
FILE *f = fopen(...);
// Creating a reader. Each reader stores a function ptr to a destructor
// which closes the file if required and an internal state object.
Reader *r = FileReader(f);
// -or- 
Reader *r = CharReader(str);
// Start parsing ---------------------------
// Inside the parser, repeated calls to:
int error = ReadBytes(&buf /* target buf */, &nRead /* n read out */, maxBytes /* max to read */);
// End parsing -----------------------------
CloseReader(&r); // calls destructor, free's state, self

我想保持简单。有没有其他明显的方法可以使用我错过的更少的基础设施来实现这一点?

注意:为了强调编程接口方面的问题,我已经对其进行了相当大的简化。它实际上在内部使用了wchar_t和大量编码内容,有点像老鼠窝,我会同时解开它。


感谢所有回答的人。最干净的答案是使用fmemopen。我在下面提供了一个完整的例子:

#include <stdio.h>
#include <string.h>
void dump(FILE *f) {
        char c;
        while ((c = fgetc(f)) != EOF)
                putchar(c);
}
int main(int argc, char *argv[]) {
        /* open string */
        const char str[] = "Hello string!n";
        FILE *fstr  = fmemopen(&str, strlen(str), "r");
        /* open file */
        FILE *ffile = fopen("hello.file", "r");
        /* dump each to stdout */
        dump(ffile);
        dump(fstr);
        /* clean up */
        fclose(ffile);
        fclose(fstr);
}

您的基础结构中甚至不需要CharReader。相反,当内存缓冲区的布局与文件相同时,以下内容应该有效:

const char *str = "stringToParse";
FILE *f = fmemopen(str, strlen(str), "r");
Reader *r = FileReader(f);
// use FileReader to read from string...

很难有一个比"create_resource"、"use_resource"one_answers"free_resource"更简单的API。从抽象的角度来看,这似乎很合理。

我认为&nRead是ReadBytes的流读取器参数吗?如果不是,ReadBytes如何指示要处理哪个流?(如果这是您要处理的仅流,那么您可以不命名资源,只需在ReadBytes中引用唯一的资源。但在这种情况下,Reader和CloseReader也不需要返回流实体)。

相关内容