A reader interface that consumes FILE and char * in C

I am modifying a parser that I have inherited, which currently only reads from FILE * via read. Now he has a need to be able to extract data from char * constants so that inline text inside C lines can be parsed.

I have considered providing a simple interface both in the form of "readers" and for reading files and a char reader from which the parser can capture characters. For instance:

// 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 state, self

I would like it to be very simple. Are there any obvious other ways to achieve this using less infrastructure that I missed?

. , , . 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);
}
0
2

CharReader . , , :

const char *str = "stringToParse";
FILE *f = fmemopen(str, strlen(str), "r");

Reader *r = FileReader(f);

// use FileReader to read from string...
+3

API, "create_resource", "use_resource", "free_resource". , .

& nRead - ReadBytes? , ReadBytes , ? ( , , ReadBytes. Reader CloseReader ).

0

All Articles