I have a bad feeling that the answer to this question is “no”, but I wanted to throw this out there in case anyone has any clever ideas.
I have a set of output routines that take a complex data structure and print it in a textual format. They have prototypes like:
void print_mystruct(struct mystruct *s, FILE *stream)
I wrote it this way so that I can get efficient, buffered output to the terminal, to a file, to the network, etc.
Unfortunately, there’s no way that I know of, using standard C99, that I can use these same routines to build up a string in memory.
So my questions are:
- is there any clever way that I can efficiently use fputs(), fprintf(), etc. to output to a string?
- if not, is there a better paradigm that can efficiently do both buffered file output and string building? The best I can think of is to have my own structure with a vtable (instead of a FILE*). The vtable would have an output function that would either append to a string or call fwrite. But then I’d have to create printf wrappers also.
Any other clever ideas?
EDIT: I have discovered that fmemopen() is part of POSIX.1-2008 (see: fmemopen()) but is not widely supported, at least according to the GNU libc manpage.
There’s no portable way of doing this. glibc systems(linux) have open_memstream/fmemopen , other systems might not have something like it.
The portable way is to write to a file and read it back into a string. , or to separate the concerns. Instead of implementing
You’d e.g. implement
Which dynamically allocates a string(Or pass in a buffer), formats it to a string with standard string functions (snprintf etc.) and have the caller decide whether to write that to a FILE*