placing output of printf in memory: formatting strings

Steve Summit scs at adam.mit.edu
Thu Jun 20 09:37:52 AEST 1991


In article <80463 at eerie.acsu.Buffalo.EDU> luntz at acsu.buffalo.edu (jon e luntz) writes:
>What I'd
>like to do is to be able to write formatted output to memory, such as that from
>a printf or fprintf.  Is there any way to fopen a string pointer or a memory 
>location, or maybe some way to redirect output to memory temporarily?

Well, so far we've had two identical answers, but I'm not sure
they're what Mr. Luntz was looking for.  (I suspect he knows about
sprintf, although it is an obvious answer if you only read every
third word of the original question.)

What Mr. Luntz probably wants to do is something like

	extern FILE *stropen();
	char buf[80];
	FILE *sfp = stropen(buf, "w");
	fprintf(sfp, "Hello, ");
	fputs("world!", sfp);
	putc('\n', sfp);

which would leave the conglomerate string "Hello, world!\n" in buf.
Note that sfp is an apparently-ordinary FILE *, upon which any
sequence of stdio output operations can be performed, except that
the text simply accumulates in buf rather than being written to
some "file."

Note that if you have stropen (or something like it) and
vfprintf, you can implement sprintf in terms of it.

I'm not sure how Mr. Luntz plans to empty the buffer as its
characters are consumed by his "device driver."  More useful
would be a way to arrange for the characters "written" to a FILE *
to be neither written to a "file" nor accumulated in a string,
but rather passed to a user-defined output function.  Something
like:

	int mywrite(char *chars, int nchars)
	{
	}

	extern FILE *funopen();

	FILE *fp = funopen((int (*)())NULL, mywrite);

Either Chris Torek or I can supply you with stdio implementations
which let you do these sorts of things.  (funopen or its
equivalent actually takes a few more arguments, but I can't
remember how mine or Chris's works.)  Unfortunately, the extended
string and function I/O functions (i.e. stropen and funopen) are
nowhere near standard.

                                            Steve Summit
                                            scs at adam.mit.edu



More information about the Comp.lang.c mailing list