Xref: utzoo comp.unix.wizards:15158 comp.lang.c:17113 Path: utzoo!utgpu!watmath!rbutterworth From: rbutterworth@watmath.waterloo.edu (Ray Butterworth) Newsgroups: comp.unix.wizards,comp.lang.c Subject: Re: How to predict size of outcome of vsprintf? Message-ID: <24451@watmath.waterloo.edu> Date: 22 Mar 89 15:55:14 GMT References: <993@etnibsd.UUCP> <9872@smoke.BRL.MIL> <28831@bu-cs.BU.EDU> <16491@mimsy.UUCP> Organization: U of Waterloo, Ontario Lines: 40 In article <16491@mimsy.UUCP>, chris@mimsy.UUCP (Chris Torek) writes: > In article bader+@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).