I m looking for a way to pass in a FILE *
to some function so that the function can write to it with fprintf
. This is easy if I want the output to turn up in an actual file on disk, say. But what I d like instead is to get all the output as a string (char *
). The kind of API I d like is:
/** Create a FILE object that will direct writes into an in-memory buffer. */
FILE *open_string_buffer(void);
/** Get the combined string contents of a FILE created with open_string_buffer
(result will be allocated using malloc). */
char *get_string_buffer(FILE *buf);
/* Sample usage. */
FILE *buf;
buf = open_string_buffer();
do_some_stuff(buf); /* do_some_stuff will use fprintf to write to buf */
char *str = get_string_buffer(buf);
fclose(buf);
free(str);
The glibc headers seem to indicate that a FILE can be set up with hook functions to perform the actual reading and writing. In my case I think I want the write hook to append a copy of the string to a linked list, and for there to be a get_string_buffer
function that figures out the total length of the list, allocates memory for it, and then copies each item into it in the correct place.
I m aiming for something that can be passed to a function such as do_some_stuff
without that function needing to know anything other than that it s got a FILE *
it can write to.
Is there an existing implementation of something like this? It seems like a useful and C-friendly thing to do -- assuming I m right about the FILE
extensibility.