How to predict size of outcome of vsprintf?

Ray Butterworth rbutterworth at watmath.waterloo.edu
Thu Mar 23 01:55:14 AEST 1989


In article <16491 at mimsy.UUCP>, chris at mimsy.UUCP (Chris Torek) writes:
> In article <wY9m4Hy00UkaI=3Ihb at andrew.cmu.edu> bader+ at andrew.cmu.edu
> (Miles Bader) writes:
> >What I'd really like would be a new function that could act as a basis
> >for all the other printf functions, and make it possible to emulate
> >them in nice ways.
> >
> >I would make it a varargs function that takes a bounded output buffer
> >and is restartable at the point where it stops due to running into the
> >end of the buffer.
> 
> This is fairly difficult to implement (one wants coroutines for something
> like this).  Instead, why not allow stdio streams to `read' and `write'
> via user-provided functions?  Everyone knows how to use read() and
> write(); simply provide your own write() that mallocs space, or prints
> in a window, or whatever.

There is something else that is usually fairly easy to implement though,
even if the code for the implementation is non-portable.

A typical implementation of sprintf simply builds a FILE* and calls
fprintf on it, while a typical implementation of stdio has some
function that is called when an output buffer fills.

One could easily write a function that is similar to sprintf but is
passed a pointer to the buffer size.  When the buffer fills up,
instead of "flushing" it, realloc is called and the fprintf continues.
The function would return the pointer to the possibly reallocated
buffer and would possibly have stuffed a new size through the
buffer size pointer.

In many stdio implementations this can be written with only a few
lines of code, and I'd say it is far more useful than many of the
alternatives that have been suggested.
e.g. a function that returns an estimate of how many characters
would be needed (this doubles the cpu since it effectively calls
printf twice), or a function that limits the output to the buffer
(you have to check if the buffer filled, and if it did you have
to realloc another bigger one and call the function right from
the beginning again).



More information about the Comp.unix.wizards mailing list